当前位置: 首页 > 知识库问答 >
问题:

Spring-OAUTH2.0:调用 /oauth/token时没有可用资源错误

文华美
2023-03-14

我们有一组ReST服务,我们需要使用OAUTH2.0来保护它们。我正在尝试通过参考以下资源来实现OAUTH2.0:

  • 2腿(客户端凭据)OAuth2服务器的Spring Security上下文设置
  • http://www.e-zest.net/blog/rest-authentication-using-oauth-2-0-resource-owner-password-flow-protocol/

但是,在完成所需的配置后,我正在尝试点击URL
http://localhost:8080/{项目名称}/oauth/Token?grant_type=密码

Tomcat 引发错误 - 请求的资源不可用。

当我试图在<code>ClientDetailsServiceImpl中放置调试点时。java,流带有正确的细节。无法理解我在这里做错了什么。任何建议都将不胜感激。蒂亚。

以下是文件的详细信息:< br> Spring配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd ">


    <http pattern="/oauth/token" create-session="stateless"
        authentication-manager-ref="authenticationManager"
        xmlns="http://www.springframework.org/schema/security" > 
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> 
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <http pattern="/resources/**" create-session="never"
        entry-point-ref="oauthAuthenticationEntryPoint"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/resources/**" method="GET" access="IS_AUTHENTICATED_FULLY" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <http pattern="/logout" create-session="never" 
        entry-point-ref="oauthAuthenticationEntryPoint"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/logout" method="GET" />
        <sec:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler"   />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <bean id="logoutSuccessHandler" class="in.test.server.security.oauth.LogoutImpl" >
        <property name="tokenstore" ref="tokenStore"></property>
    </bean>

    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    </bean>

    <bean id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="springsec/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">
    </bean>

    <bean id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <authentication-manager alias="authenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>

    <bean id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>

    <bean id="clientDetails" class="in.test.server.security.oauth.ClientDetailsServiceImpl"/>

    <authentication-manager id="userAuthenticationManager" 
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider  ref="customUserAuthenticationProvider">
        </authentication-provider>
    </authentication-manager>

    <bean id="customUserAuthenticationProvider"
        class="in.test.server.security.oauth.CustomUserAuthenticationProvider">
    </bean>

    <oauth:authorization-server
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
        <oauth:authorization-code />
        <oauth:implicit/>
        <oauth:refresh-token/>
        <oauth:client-credentials />
        <oauth:password authentication-manager-ref="userAuthenticationManager"/>
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter"
        resource-id="springsec" token-services-ref="tokenServices" />

    <bean id="tokenStore"
        class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />

    <bean id="tokenServices" 
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="supportRefreshToken" value="true" />
        <property name="accessTokenValiditySeconds" value="300000"></property>
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>


    <mvc:annotation-driven />   <!-- Declares explicit support for annotation-driven MVC controllers  @RequestMapping, @Controller -->

    <mvc:default-servlet-handler />

    <bean id="MyResource" class="in.test.server.resource.CommonResource"></bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>in-test-gcp-server</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
            classpath:security-config.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>in.test.server.resource.TestRSApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Added for Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

ClientDetailsServiceImpl.java

package in.test.server.security.oauth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.BaseClientDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Service;

@Service
public class ClientDetailsServiceImpl implements ClientDetailsService {

    public ClientDetails loadClientByClientId(String clientId)
            throws OAuth2Exception {
if (clientId.equals("client1")) {

            List<String> authorizedGrantTypes=new ArrayList();
            authorizedGrantTypes.add("password");
            authorizedGrantTypes.add("refresh_token");
            authorizedGrantTypes.add("client_credentials");

            BaseClientDetails clientDetails = new BaseClientDetails();
            clientDetails.setClientId("client1");
            clientDetails.setClientSecret("client1");
            clientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);

            return clientDetails;

        } else if(clientId.equals("client2")){

            List<String> authorizedGrantTypes=new ArrayList();
            authorizedGrantTypes.add("password");
            authorizedGrantTypes.add("refresh_token");
            authorizedGrantTypes.add("client_credentials");


            BaseClientDetails clientDetails = new BaseClientDetails();
            clientDetails.setClientId("client2");
            clientDetails.setClientSecret("client2");
            clientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);

            return clientDetails;
        }


        else{
            throw new NoSuchClientException("No client with requested id: "
                    + clientId);
        }
    }




}

CustomUserAuthenticationProvider.java

package in.test.server.security.oauth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

public class CustomUserAuthenticationProvider implements AuthenticationProvider{

    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        if(authentication.getPrincipal().equals("user")&& authentication.getCredentials().equals("user"))
        {

            List<GrantedAuthority> grantedAuthorities = new ArrayList();
            UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),grantedAuthorities);


            return auth;

        }
        else if(authentication.getPrincipal().equals("admin")&& authentication.getCredentials().equals("admin"))
        {
            List<GrantedAuthority> grantedAuthorities = new ArrayList();
            UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),grantedAuthorities);

            return auth;
        }
        else if(authentication.getPrincipal().equals("user1")&& authentication.getCredentials().equals("user1"))
        {
            List<GrantedAuthority> grantedAuthorities = new ArrayList();
            UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),grantedAuthorities);

            return auth;
        }
        else{
                throw new BadCredentialsException("Bad User Credentials.");
        }
    }

    public boolean supports(Class<?> arg0) {
        // TODO Auto-generated method stub
        return true;
    }






}

共有1个答案

孟德曜
2023-03-14

在您的web.xml中,您需要一个servlet映射标签,该标签具有指向 /oauth/token的url-mode属性

类似于:

<servlet-mapping>
    <servlet-name>spring <!-- Or whatever your dispatch servlet is called --></servlet-name>
    <url-pattern>/oauth/token</url-pattern>
</servlet-mapping>
 类似资料:
  • 你知道我做错了什么吗 我的spring-security配置:

  • 在尝试将我们的web应用程序与Spring Oauth2集成时遇到了问题 endpoint/oauth/token被映射为GET和POST方法 访问时间:https://192.168.70.19:8072/oauth/token?grant_type=password&client_id=7ca42ea39288ec73212716fc6a51b8a2&username=admin&passwo

  • 我正在尝试构建一个基于Spring的web应用程序,我想从配置一个基于存储在数据库表中的用户名和密码元组的简单身份验证系统开始。 我的理解是,使用Spring security可以很容易地实现这一点,但我无法使其工作。 下面是我的web.xml文件。 跟随servlet-context.xml文件。bob和sam用户用于测试目的。在我得到这个权利之后,我将切换到一个基于JDBC的用户服务。 当我将

  • 在最近升级了我的android工作室后,我不能再构建我的项目了。 下面显示了我的gradle.build文件: 如有任何帮助,不胜感激。

  • 我正在用c语言(使用openwrt作为操作系统)构建一个项目,将文件上载到FTP服务器。我对传入的数据使用MQTT。因此,对于我订阅的每个主题,我都会保存这些数据,然后将其上载到FTP服务器,为了使事情顺利进行,每次需要上载文件时,我都会使用一个线程来完成这项工作。为了确保程序不会运行太多线程,允许每个主题创建一个线程。我使用了一个变量(比如mutex,但它不是pthread\u mutex\t,

  • 以下是错误日志: 这里有一个相关的问题:https://stackoverflow.com/a/14370767,它建议使用SO_SNDTIMEO套接字选项设置发送超时。