【问题标题】:RESTful Authorization checkRESTful 授权检查
【发布时间】:2017-05-24 00:47:45
【问题描述】:

我有一个 RESTful Web 应用程序,想要实现基于令牌的身份验证。我能够发出一个令牌拦截带有过滤器类的请求,如下所示:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JpaConfiguration jpaConfiguration;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // disable caching
        http.headers().cacheControl();          
        http.csrf().disable() // disable csrf for our requests.
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            .anyRequest().authenticated()
            .and()
            // Here the login requests is filtered
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
            // Much probably here I have to filter other requests to check the presence of JWT in header,
            // here i just add a commented block with teh name of the Filter
                //.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                ;
            }
    }

JWTLoginFilter 类如下所示:

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    private TokenAuthenticationService tokenAuthenticationService;
public JWTLoginFilter(String url, AuthenticationManager authenticationManager) {
     super(new AntPathRequestMatcher(url));
     setAuthenticationManager(authenticationManager);
     tokenAuthenticationService = new TokenAuthenticationService();
}

 @Override
 public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
 throws AuthenticationException, IOException, ServletException {
     ServletInputStream inputStream = httpServletRequest.getInputStream();
     httpServletRequest.getCharacterEncoding();

     ObjectMapper mapper = new ObjectMapper();
     AccountCredentials credentials = mapper.readValue(inputStream, AccountCredentials.class);

     UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
     return getAuthenticationManager().authenticate(token);
 }
 @Override
 protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
 throws IOException, ServletException {
     String name = authentication.getName();
     tokenAuthenticationService.addAuthentication(response, name);
     }
}

哪个类应该扩展JWTAuthenticationFilter以拦截请求?

还是 AbstractAuthenticationProcessingFilter 类吗?

有没有更好的方法来开发基于令牌的身份验证?

【问题讨论】:

    标签: token access-token restful-authentication restful-architecture


    【解决方案1】:

    所以我终于找到了解决办法:

    public class JWTAuthenticationFilter extends GenericFilterBean implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            try{
                ...
    
                SecurityContextHolder.getContext().setAuthentication(token);
                chain.doFilter(servletRequest, response);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    

    JWTAuthenticationFilter 扩展了 GenericFilterBean 类,并且必须实现一个 spring 安全过滤器,doFilter 方法可以解决问题。

    注意:你必须从 FilterChain 类中调用 doFilter 方法,否则你是新来的端点,我对此很着迷。

    【讨论】:

      【解决方案2】:

      我不知道为什么要使用 JWTLoginFilter。我正在开发一个由 OAuth2 保护的 RESTful 项目。总而言之,请求者必须将访问令牌与 REST API 一起传递以进行授权。

      以下是可能作为参考的示例

      @Configuration
      @EnableResourceServer
      public class Oauth2AuthConfiguration implements ResourceServerConfigurer {
            @Autowired
            private OAuth2RemoteTokenServices tokenServices;
      
            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
                resources.tokenServices(tokenServices);
            }
      
            @Override
            public void configure(HttpSecurity httpSecurity) throws Exception {
               httpSecurity.exceptionHandling()
                  .accessDeniedHandler(new PPDAccessDeniedHandler())
                  .authenticationEntryPoint(new PPDAuthenticationEntryPoint())
                  .and()
              .authorizeRequests()
                  .antMatchers(POST, "/api/test").hasAuthority("PARTNER");
            }
      }
      

      OAuth2RemoteTokenServices.java

      public class OAuth2RemoteTokenServices implements ResourceServerTokenServices{
          //implement how you can validate token here
          // reference: org.springframework.security.oauth2.provider.token.RemoteTokenServices
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-08
        • 2011-07-07
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        相关资源
        最近更新 更多