背景
項目中前后端通信時眠冈,有需求權(quán)限認(rèn)證的步驟飞苇,這里使用SpringSecurtiy + Jwt 采用token驗證的方式完成登錄功能。
步驟
- 添加配置類
/**
* Created by Justin on 2017/6/2.
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
// 指定加密方式
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilter() throws Exception {
return new JwtAuthenticationTokenFilter();
}
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
// 設(shè)置UserDetailsService
.userDetailsService(this.userDetailsService)
// 設(shè)置passwordEncoder
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 由于使用的是JWT蜗顽,我們這里不需要csrf
.csrf().disable()
// 基于token布卡,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// .antMatchers("/**").permitAll() // FOR TEST
// 允許對于網(wǎng)站靜態(tài)資源的無授權(quán)訪問
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/bower_components/**",
"/file/**",
"/styles/**"
).permitAll()
// 對于獲取token的rest api要允許匿名訪問
.antMatchers("/auth/**").permitAll()
// 除上面外的所有請求全部需要鑒權(quán)認(rèn)證
.anyRequest().authenticated();
// 禁止緩存
httpSecurity.headers().cacheControl();
// 添加JWT filter
httpSecurity
.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
- 添加配置(build.gradle)
# Token
token.tokenHeader=Authorization
token.tokenHead=Bearer
token.secret=mySecret
token.initRole=user