我正在尝试使用jwt来保护一个简单的Spring-Data-Rest应用程序。从https://github.com/spring-projects/spring-data-examples/tree/master/rest/security采取种子
SecurityConfig如下(使用普通用户名,密码验证)如何将其更改为JWT身份验证?
(已在存储库中使用@PreAuthorize("hasRole('ROLE_USER')")
进行授权)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* This section defines the user accounts which can be used for
* authentication as well as the roles each user has.
*/
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("greg").password("turnquist").roles("USER").and()
.withUser("ollie").password("gierke").roles("USER", "ADMIN");
}
/**
* This section defines the security policy for the app.
* - BASIC authentication is supported (enough for this REST-based demo)
* - /employees is secured using URL security shown below
* - CSRF headers are disabled since we are only testing the REST interface,
* not a web one.
*
* NOTE: GET is not shown which defaults to permitted.
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN").and()
.csrf().disable();
}
}
这是一个很好的春季启动JWT身份验证教程,但也适用于spring应用程序:https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/
根据SecurityConfiguration.configure中的教程,您需要
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
JWTAuthenticationFilter
扩展UsernamePasswordAuthenticationFilter
,应用于/ login URL并根据您的登录名/密码生成JWT令牌(如果系统中存在此类用户)。
JWTAuthorizationFilter
验证http头中的JWT令牌
当然,您需要添加更多移动部件才能通过本教程启用JWT身份验证。
我按照Spring Security OAuth教程:https://projects.spring.io/spring-security-oauth/docs/oauth2.html
特别是您必须启用资源服务器。这是我的(修改过的)配置):
@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices());
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
try {
// Load the public key of the authorization server.
String key = IOUtils.toString(getClass().getResource("/reng0-public.key"), Charset.forName("US-ASCII"));
converter.setVerifierKey(key);
} catch (IOException e) {
throw new RuntimeException(e);
}
return converter;
}
@Bean
@Primary
public ResourceServerTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
}
客户端必须添加Authorization:Bearer标头才能使其正常工作。