搭建认证服务器
WebSecurityConfig
认证服务器,管理token,发放认证token等功能。但是首先他是一个认证服务器,认证,说白了就是需要用户名和密码,判断用户身份,校验用户权限。这部分是spring-security的职责,可以当成是一个纯纯的security应用,按原有套路配置即可。
配置如下:
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/actuator/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable()
.formLogin()
;
}
/**
* 授权验证服务
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
.withUser("simm").password(passwordEncoder().encode("123")).roles("USER").and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("USER","ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
- 这里只是配置了两个内存用户,没什么其他的了。
下面配置一直mvc的端点:
@RestController
public class EndPoint {
@RequestMapping("/hello")
@RolesAllowed("ROLE_ADMIN") // JSR-250
@Secured({"ROLE_ADMIN"}) //securedEnabled
public String hello() {
SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().forEach(x-> System.out.println(((GrantedAuthority) x).getAuthority()));
return "asd";
}
@RequestMapping("/changePassword")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String changePassword(long userId ){
return "hello2";
}
}
- 注意这里对于权限验证的几种写法。
AuthorizationServerConfig
下面来配置认证服务器
注意:
- 认证服务器本质上也是对一些url的拦截处理,和webSecurity一样是基于过滤器链的。他的优先级是高于webSercurity的。
- 因为EnableAuthorizationServer会导入AuthorizationServerSecurityConfiguration,他的@Order(0),并且继承WebSecurityConfigurerAdapter
- 这里就有了两个WebSecurityConfigurerAdapter,按order,是authServer的配置先生效,所以原来的不会处理oauth开头的请求了,而都是到了authServer来处理。