Bootstrap

Spring boot 入门教程-在Spring Security+Oauth2

@Autowired

@Qualifier(“authenticationManagerBean”)

private AuthenticationManager authenticationManager;

@Autowired

@Qualifier(“dataSource”)

private DataSource dataSource;

@Autowired

private UserDetailsService userDetailsService;

@Bean

public TokenStore tokenStore() {

// return new InMemoryTokenStore(); //使用内存中的 token store

return new JdbcTokenStore(dataSource); ///使用Jdbctoken store

}

@Override

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.jdbc(dataSource)

.withClient(“client”)

.secret(new BCryptPasswordEncoder().encode(“123456”))

.authorizedGrantTypes(“password”, “refresh_token”)//允许授权范围

.authorities(“ROLE_ADMIN”,“ROLE_USER”)//客户端可以使用的权限

.scopes( “read”, “write”)

.accessTokenValiditySeconds(7200)

.refreshTokenValiditySeconds(7200);

}

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

endpoints.tokenStore(tokenStore())

.authenticationManager(authenticationManager)

.userDetailsService(userDetailsService);//必须设置 UserDetailsService 否则刷新token 时会报错

}

@Override

public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

security

.tokenKeyAccess(“permitAll()”)

.checkTokenAccess(“isAuthenticated()”)

.allowFormAuthenticationForClients();//允许表单登录

}

}

4.配置资源服务器

@Configuration

@EnableResourceServer //这个类表明了此应用是OAuth2 的资源服务器,此处主要指定了受资源服务器保护的资源链接

public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override

public void configure(HttpSecurity http) throws Exception {

http.csrf().disable()//禁用了 csrf 功能

.authorizeRequests()//限定签名成功的请求

.antMatchers(“/decision/“,”/govern/”).hasAnyRole(“USER”,“ADMIN”)

.antMatchers(“/admin/**”).hasRole(“ADMIN”)

.antMatchers(“/test/**”).authenticated()//必须认证过后才可以访问

.anyRequest().permitAll()//其他没有限定的请求,允许随意访问

.and().anonymous();//对于没有配置权限的其他请求允许匿名访问

}

}

5.对WebSecurityConfig 进行修改,因为加入了oauth 2.0 的配置,所以该文件之前的权限设置可以删掉,访问控制交给资源服务器只保留“/oauth/**,“/login/**”,”/logout/**",修改后的WebSecurityConfig

@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired

private UserDetailsService userDetailsService;

@Bean

public PasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}

@Bean

public AuthenticationManager authenticationManagerBean() throws Exception {

return super.authenticationManagerBean() ;

}

/**

  • 配置用户签名服务 主要是user-details 机制,

  • @param auth 签名管理器构造器,用于构建用户具体权限控制

  • @throws Exception

*/

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.userDetailsService(userDetailsService)

.passwordEncoder(passwordEncoder());

}

/**

  • 用来配置拦截保护的请求

  • @param http

  • @throws Exception

*/

@Override

protected void configure(HttpSecurity http) throws Exception {

//不拦截 oauth 开放的资源

http.csrf().disable();

http.requestMatchers()//使HttpSecurity接收以"/login/“,”/oauth/"开头请求。

.antMatchers(“/oauth/", "/login/”, “/logout/**”)

.and()

.authorizeRequests()

.antMatchers(“/oauth/**”).authenticated()

.and()

.formLogin();

}

}

到这整合就完成了。

获取token :

[http://localhost:18088/oa 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 uth/token?username=admin&password=admin&grant_type=password&client_id=client&client_secret=123456&grant_type=refresh_token](()

返回:

{

“access_token”: “624d8e84-e981-484b-a064-1d8f5997e4fb”,

“token_type”: “bearer”,

“refresh_token”: “ca0d41c8-d808-4211-8cab-5da5bfe6c6db”,

“expires_in”: 5696,

“scope”: “read write”

}

刷新令牌:

[http://localhost:18088/oauth/token?grant_type=refresh_token&client_id=client&client_secret=123456&refresh_token=ca0d41c8-d808-4211-8cab-5da5bfe6c6db](()

返回数据:

{

“access_token”: “75b23bfc-c0d5-425f-b780-df8fff60d256”,

“token_type”: “bearer”,

“refresh_token”: “ca0d41c8-d808-4211-8cab-5da5bfe6c6db”,

“expires_in”: 7199,

“scope”: “all read write”

}

大功告成!

补充:客户端模式:

授权服务器增加配置如下:

.and().withClient(“client_1”)

.secret(passwordEncoder().encode(“123456”))

.authorizedGrantTypes(“client_credentials”)

.scopes(“read”, “write”)

;