Java Spring安全:为什么.authorizeRequests().antMatchers(";/api/v1/web/**";).permitAll()不工作?
我很难使用JWT令牌访问Java Spring安全:为什么.authorizeRequests().antMatchers(";/api/v1/web/**";).permitAll()不工作?,java,spring-boot,spring-security,jwt,Java,Spring Boot,Spring Security,Jwt,我很难使用JWT令牌访问/api/v1/web/**URI。此URI必须是公共的。我知道这是许多应用程序中的常见功能,否则,我们如何创建登录、登录和重置密码页面?因此,我确信我犯了一些愚蠢的错误,因为我没有太多的Spring引导/安全经验 以下是我的web安全配置代码: @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowire
/api/v1/web/**
URI。此URI必须是公共的。我知道这是许多应用程序中的常见功能,否则,我们如何创建登录、登录和重置密码页面?因此,我确信我犯了一些愚蠢的错误,因为我没有太多的Spring引导/安全经验
以下是我的web安全配置代码:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.customAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// disable caching
http.headers().cacheControl();
/*ROUTING SECURITY*/
http.csrf().disable() // disable csrf for our requests.
.cors()
.and()
.authorizeRequests()
.antMatchers("/api/v1/web/**").permitAll()
.antMatchers( "/api/v1/users/**" ).hasAnyAuthority("USERS_LIST,USERS_CREATE,USERS_EDIT,USERS_DELETE")
.antMatchers( "/api/v1/locals/**" ).hasAnyAuthority("LOCALS_LIST,LOCALS_CREATE,LOCALS_EDIT,LOCALS_DELETE")
.antMatchers( "/api/v1/utils/**" ).hasAnyAuthority("UTILS")
.anyRequest().authenticated()
.and()
// We filter the api/login requests
.addFilterBefore(new JWTLoginFilter("/api/v1/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
// And filter other requests to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
// @Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/api/v1/web/**");
// }
}
以下是我的身份验证:
public class TokenAuthenticationService {
private final String secret = "secret_string";
private final String tokenPrefix = "Bearer ";
private final String headerString = "Authorization";
public void addAuthentication(HttpServletResponse response, Authentication authentication) {
GregorianCalendar expiration = new GregorianCalendar();
expiration.add(GregorianCalendar.HOUR_OF_DAY, 5);
//expiration.add(GregorianCalendar.SECOND, 10);
List<UserAuthority> authorities = new ArrayList<UserAuthority>();
for( GrantedAuthority authority : authentication.getAuthorities() ) {
authorities.add( new UserAuthority( authority.getAuthority() ) );
}
AuthenticatedUser authenticatedUser = new AuthenticatedUser( (String)authentication.getPrincipal(), authorities );
String dataToGenerateToken;
try {
dataToGenerateToken = new ObjectMapper().writeValueAsString( authenticatedUser );
// We generate a token now
String generatedToken = Jwts.builder()
.setSubject( dataToGenerateToken )
.setExpiration( expiration.getTime() )
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
response.addHeader(headerString, tokenPrefix + generatedToken);
response.addHeader("Access-Control-Expose-Headers", "Authorization");
response.getWriter().write( dataToGenerateToken );
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(headerString).substring(7);
if (token != null) {
// parse the token.
String userData = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
if (userData != null) // we managed to retrieve a user
{
AuthenticatedUser authenticatedUser;
try {
authenticatedUser = new ObjectMapper().readValue(userData, AuthenticatedUser.class);
return authenticatedUser;
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}
如果我删除此代码的注释:
// @Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/api/v1/web/**");
// }
我只能在/api/v1/web/**
uri下执行SELECT查询,如果我试图调用保存对象(更新或插入)的服务,则会出现事务性错误。很奇怪,我知道
有什么想法吗
谢谢大家的帮助,我意识到我做错了什么,以下是我的最终解决方案:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.customAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// disable caching
http.headers().cacheControl();
/*ROUTING SECURITY*/
http.csrf().disable() // disable csrf for our requests.
.cors()
.and()
.authorizeRequests()
.antMatchers("/api/v1/web/**").permitAll()
.and()
.authorizeRequests()
.antMatchers( "/api/v1/users/**" ).hasAnyAuthority("USERS_LIST,USERS_CREATE,USERS_EDIT,USERS_DELETE")
.antMatchers( "/api/v1/locals/**" ).hasAnyAuthority("LOCALS_LIST,LOCALS_CREATE,LOCALS_EDIT,LOCALS_DELETE")
.antMatchers( "/api/v1/utils/**" ).hasAnyAuthority("UTILS")
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTLoginFilter("/api/v1/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
在TokenAuthenticationService
类中,我将getAuthentication方法的第一行编辑为:
public Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(headerString);
if (token != null) {
token = token.substring(7);
....
}
现在,我的应用程序已经配置好,可以正确地访问公共和私有URI。不再需要
web.ignering()
。第61行是什么?它是String-token=request.getHeader(headerString.substring)(7)代码>?您不能在null
上调用substring
。最后一个错误是@dur。我不敢相信:(至少现在我可以使用antMatchers()
正确地配置安全性,而且我不需要使用web.ignering()
不再。非常感谢。请接受副本。它实际上只是一个NullPointerException
。该问题对其他用户没有价值。这对您没有坏处,因为您的问题是经过投票的。
public Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(headerString);
if (token != null) {
token = token.substring(7);
....