在没有XML配置的情况下实现Spring Security Oauth

时间:2014-09-23 20:46:38

标签: java oauth spring-security oauth-2.0 spring-security-oauth2

我尝试使用OAuth 2.0身份验证和授权构建一个使用Spring Security保护的基本REST服务。

我试图限制所涉及的元素,因此我不是复制粘贴依赖于Spring Beans,Spring MVC等的Spring Security Oath XML配置,而是直接使用Spring Security Oauth类。

在尝试从/ oauth / token获取访问令牌时,我遇到了麻烦。我可能遗漏了一些基本的东西,但是Spring Security和Spring Security Oauth都难以理解,我似乎无法找到一个不需要使用额外框架的示例或教程

谁能看到我出错的地方?

RestService.java

@Path("/members")
public class RestService {

    @Secured({"ROLE_USER"})
    @GET
    @Path("/{id}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response readMember(@PathParam("id") String id) {

        String output;
        if(Integer.valueOf(id) < members.size())
        {
            output = members.get(Integer.valueOf(id)).toString();
        }
        else
        {
            output = "No such member.";
        }

        return Response.status(200).entity(output).build();
    }
}

OAuthServices.java

public class OAuthServices {

    static private DefaultTokenServices tokenServices = new DefaultTokenServices();
    static private InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();

    static {
        Map<String, ClientDetails> clientDetailsStore = new HashMap<String, ClientDetails>();
        BaseClientDetails clientDetails = new BaseClientDetails("client", "resource", null, null, "read,write");
        clientDetailsStore.put("client", clientDetails);
        clientDetailsService.setClientDetailsStore(clientDetailsStore);
    }

    public static DefaultTokenServices getTokenServices() {
        return tokenServices;
    }

    public static InMemoryClientDetailsService getClientDetailsService() {
        return clientDetailsService;
    }
}

SecurityConfig.java

@EnableAuthorizationServer
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements AuthorizationServerConfigurer {

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER")
                    .and()
                    .withUser("admin").password("password").roles("USER", "ADMIN");
        }

    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)
            throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        // TODO Auto-generated method stub

    }
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>jersey-helloworld-servlet</servlet-name>
        <servlet-class>
                     org.glassfish.jersey.servlet.ServletContainer
                </servlet-class>
                <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.excentus.springsecurity.rest.test</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-helloworld-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

1 个答案:

答案 0 :(得分:0)

我可以看到2个错误(可能不是整个故事)。

  1. 您正在使用web.xml,但此处未定义Spring Security过滤器。它是锅炉板代码,但你必须这样做(除非你转而采用更现代的方式用Spring Boot编写应用程序)。示例(来自docs):

      springSecurityFilterChain   org.springframework.web.filter.DelegatingFilterProxy

      springSecurityFilterChain   / *

  2. 您已实施AuthorizationServerConfigurer但未实施任何方法。您至少需要提供客户详细信息,例如(来自[integration tests(https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/vanilla/src/main/java/demo/Application.java)):

        @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("my-trusted-client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(60);
    }
    
  3. 你的静态便利课OAuthServices也是一种反模式,但它不会破坏任何东西(我也没有看到它被用在任何地方,但可能会错过它)。 / p>