Spring Security忽略URL作为过滤器



我有一个扩展AbstractAuthenticationProcessingFilter的自定义过滤器,不想在所有页面上调用它。例如,我想忽略/login。我把它添加到我的网页上。忽略,但不是忽略任何东西。这里我读到安全系统确实执行过滤器,但如果请求被阻止则忽略。但是我的过滤器被调用并阻止了所有请求。

SecurityConfig

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtAuthenticationProvider authenticationProvider;
@Autowired
protected JwtAccessDeniedHandler accessDeniedHandler;
@Autowired
protected JwtAuthenticationFailureHandler authenticationFailureHandler;
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return new ProviderManager(Arrays.asList(authenticationProvider));
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/")
.antMatchers("/api/login")
.antMatchers("/api/register")
.antMatchers("/api/contacts/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and()
.authorizeRequests().anyRequest().hasRole("ADMIN")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
http
.addFilterBefore(getNewFilter(), UsernamePasswordAuthenticationFilter.class);

}
public JwtAuthenticationFilter getNewFilter() throws Exception {
JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManager());
authenticationTokenFilter.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
authenticationTokenFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
return authenticationTokenFilter;
}
}

JwtAuthenticationFilter

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter() {
super("/**"); // I tried changing this but I don't see a difference
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
System.out.println("Attempt Authentication");
Cookie cookie = WebUtils.getCookie(request, "auth");
if (cookie == null || cookie.getValue() == null) {
System.out.println("No Jwt Token existing");
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String authToken = cookie.getValue();
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
System.out.println("AuthRequest Created");
return getAuthenticationManager().authenticate(authRequest);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
System.out.println("successful authentication");
chain.doFilter(request, response);
}
}

JwtAuthenticationProvider

@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Autowired
AccountToContactService accountToContactService;
public static final String schoolAbbreviation = "stg";
@Override
public boolean supports(Class<?> authentication) {
return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
System.out.println("AdditionalChecks");
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
String tokenString = jwtAuthenticationToken.getToken();
System.out.println("retrieveUser");
JwtToken token = JwtToken.readToken(tokenString);
if (token == null) {
throw new JwtInvalidTokenException("Token could not be parsed.");
}
JwtClaims<?> claims = token.getClaims();
ZonedDateTime expiration = claims.getExpiration();
Long accountId = claims.getAid();
String roles = claims.getRole();
if (expiration.isAfter(ZonedDateTime.now())) {
throw new JwtTokenExpiredException("Given JWT Token is expired. Login to get a new one");
}
boolean isTeacher;
Long contactId;
ContactInformation contactInformation = claims.getContactInformation(schoolAbbreviation);
if (contactInformation == null) {
AccountToContact accountToContact = accountToContactService.findByAccountId(accountId).orElseThrow(NoContactForAccountException::new);
isTeacher = accountToContact.getContact().isTeacher();
contactId = accountToContact.getId().getContactId();
System.out.println("Contactinformation is null");
} else {
isTeacher = contactInformation.isTch();
contactId = contactInformation.getId();
System.out.println("Contactinformation is not null");
}
if (isTeacher) {
roles = roles + ",ROLE_TEACHER";
}
List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
for (GrantedAuthority auth : authorityList) {
System.out.println("Authority: " + auth.getAuthority());
}
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
return new AuthenticatedUser(contactId, "USERNAME", authorityList);
}
protected void updateJwtToken(String schoolAbbreviation, ContactInformation info, JwtToken token, HttpServletResponse response) {
token.getClaims().setContactInformation(schoolAbbreviation, info);
ZonedDateTime currentTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC"));
token.getClaims().setIssuedAt(currentTime).setExpiration(currentTime.plusMinutes(120));
String tokenString = token.build();
//Own Cookie
Cookie cookie = new Cookie();
cookie.setToken(tokenString);
cookie.setMaxAge(120*60);
response.setHeader("Set-Cookie", cookie.toString());
}
}

我对安全系统不是很有信心,从这个网站上得到了很多。希望有人能告诉我如何在过滤器中忽略url。提前感谢!

尝试在安全配置类中添加:

@Override
public void configure(final WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers("{endpoint}");
}

相关内容

  • 没有找到相关文章

最新更新