LoginWebSecurityConfigureAdapter
設定要驗證條件
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
System.out.println("LoginWebSecurityConfigureAdapter configure http security");
httpSecurity
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, Config.REGISTER_URL).permitAll()
.antMatchers("/role1").hasAuthority("role1")
.antMatchers("/role2").hasAuthority("role2")
.anyRequest().authenticated()
.and()
.addFilter(new LoginUsernamePasswordAuthenticationFilter(authenticationManager()))
.addFilter(new LoginAuthorizationFilter(authenticationManager(), loginMapper))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
;
}
這裡是設定全部路徑都要驗證,但是放過Register API
另外有設定要權限的API
- /role1要role1權限
- /role2要role2權限
還有設定要驗證的Filter
LoginUsernamePasswordAuthenticationFilter: 處理Login API的Filter
LoginAuthorizationFilter: 驗證其他API JWT的Filter
產生驗證資訊
拿使用者的帳號去產生使用者的帳戶資訊,讓LoginUsernamePasswordAuthenticationFilter檢查
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
System.out.println("LoginWebSecurityConfigureAdapter configure auth");
authenticationManagerBuilder
.userDetailsService(new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
System.out.println("LoginWebSecurityConfigureAdapter configure auth account: " + account);
LoginEntity loginEntity = loginMapper.selectMember(account);
if(loginEntity == null) {
throw new UsernameNotFoundException("could not find the account: " + account);
}
System.out.println("LoginWebSecurityConfigureAdapter login entity account: " + loginEntity.getAccount());
System.out.println("LoginWebSecurityConfigureAdapter login entity password: " + loginEntity.getPassword());
System.out.println("LoginWebSecurityConfigureAdapter login entity role1: " + loginEntity.getRole1());
System.out.println("LoginWebSecurityConfigureAdapter login entity role2: " + loginEntity.getRole2());
List<GrantedAuthority> authorities = new ArrayList<>();
if(loginEntity.getRole1() == 1) {
authorities.add(new SimpleGrantedAuthority("role1"));
}
if(loginEntity.getRole2() == 1) {
authorities.add(new SimpleGrantedAuthority("role2"));
}
User user = new User(loginEntity.getAccount(), bCryptPasswordEncoder.encode(loginEntity.getPassword()),
true, true, true, true,
authorities);
return user;
}
})
.passwordEncoder(bCryptPasswordEncoder);
}