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

如何在spring security中添加授权过滤器来验证令牌和设置安全上下文?

林俊英
2023-03-14
    null
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
  prePostEnabled = true
)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("applicationUserService")
UserDetailsService userDetailsService;

@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
  SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
  authenticationManagerBuilder
    .userDetailsService(userDetailsService)
    .passwordEncoder(bCryptPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.csrf().disable().authorizeRequests()
    .antMatchers(HttpMethod.GET, "/home").hasAnyRole("ADMIN")
    .antMatchers(HttpMethod.GET, "/login").hasAnyRole("ADMIN")
    .anyRequest().authenticated()
    .and()
    .addFilter(new AuthorizationFilter(authenticationManager()))
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
public class AuthorizationFilter extends BasicAuthenticationFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationFilter.class);

public AuthorizationFilter(AuthenticationManager authenticationManager) {
  super(authenticationManager);
}

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
  LOGGER.info("Request Info : {}", req.getRequestURI());
  // get token
  // fetch details from external API
  // set security context
  List<GrantedAuthority> authorities = new ArrayList<>();
  authorities.add((GrantedAuthority) () -> "ROLE_ADMIN");
  SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user1", null, authorities));
  LOGGER.info("security context principle:{}", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
  LOGGER.info("authorities context:{}", SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString());

  chain.doFilter(req, response);
}
@Service
@Qualifier("applicationUserService")
public class ApplicationUserServiceImpl implements UserDetailsService {

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    return new User("sidath", "123", emptyList());
  }
}

共有1个答案

邹毅
2023-03-14

请尝试以下步骤

  1. 定义AbstracTauthenticationProcessingFilter来计算请求和返回令牌。

public class AwesomeFilter extends AbstractAuthenticationProcessingFilter {
    
    public AuthorizationFilter () {
       super(new AntPathRequestMatcher("/your_post_url", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        
       // Evaluate request...
    
       // Build your custom authentication token with the info
       AwesomeToken token = new AwesomeToken();

       // Authenticate token with authentication manager
        return getAuthenticationManager().authenticate(token);
    }
public class AwesomeProvider implements AuthenticationProvider {
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      // Evaluate your custom token
      // Call your API, etc

      // Build your user authentication token details with authorities
         Collection<? extends GrantedAuthority> auths = Collections.singletonList(new 
                SimpleGrantedAuthority("ROLE_ADMIN"));
         AwesomeUserToken token = new AwesomeUserToken(auths);

      // Return user token
         return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (AwesomeToken.class.isAssignableFrom(authentication));
    }
    @Override
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
           .authenticationProvider(new AwesomeProvider());
    }

    @Override
    public void addFilters(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {

        AwesomeFilter filter = new AwesomeFilter();
        filter.setAuthenticationManager(authenticationManager);
        http
            .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }

最后,当Spring Security用filter检测到请求时,它将尝试提供程序的支持,然后用所需的权限返回令牌。

 类似资料:
  • 问题是,当比较这两个日期时,令牌将在大约17小时后过期,这是错误的,因为在生成时,令牌应该只长1分钟。 如果有人能帮助我,我非常感激

  • 如何在 Hangfire 中配置持有者令牌授权/身份验证? 我有一个自定义身份验证过滤器,它读取初始请求的身份验证令牌,但它返回401的所有其他请求(Hangfire调用)。 如何将身份令牌附加到HangFire执行的每个请求的标头中? 令牌过期后如何刷新?

  • 本文向大家介绍在axios中怎样添加授权验证?相关面试题,主要包含被问及在axios中怎样添加授权验证?时的应答技巧和注意事项,需要的朋友参考一下 在创建axios实例后

  • 我实现了一个自定义的身份验证过滤器,效果很好。在设置会话并将身份验证对象添加到安全上下文后,我使用外部身份提供程序并重定向到最初请求的URL。 安全配置 过滤逻辑 目前,我的自定义过滤器(身份确认后)只需硬编码一个角色: 然后将该身份验证对象(上面返回)添加到我的SecurityContext,然后再重定向到所需的endpoint: SecurityContextHolder.getContext

  • 我遵循了以下教程/信息来源:https://cwiki.apache.org/confluence/display/solr/authentication+and+authorization+plugins和https://lucidworks.com/blog/2015/08/17/securing-solr-basic-auth-permission-rules/ 然后我创建了这个securi

  • 我使用spring-security-oauth2-authorization-server(版本0.2.0)来实现我的授权服务器。我希望用户角色在令牌中,是否可以添加它们?喜欢 谢谢