Spring Security OAuth2开发授权服务器
2019-07-08 本文已影响0人
Nemo_fe9f
Spring Security OAuth2开发授权服务器
使用SpringCloud-oath2框架开发oath2授权服务器。
一、授权码模式
- 创建sprigboot项目
- 编写WebSecurityConfig配置文件
@Component
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailServiceImpl userDetailsService;
@Autowired
private MD5PasswordEncoder md5PasswordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService).passwordEncoder(this.md5PasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/oauth/**").permitAll()
.and().formLogin();
}
}
- 配置资源服务器
创建ResourceServerConfig配置文件
@Configuration
@EnableResourceServer
@Component
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.requestMatchers()
// 开放路径
.antMatchers("/api/**")
.and();
}
}
- 配置授权服务器
/**
* 授权服务器
*
* @author yuan 2019/7/8 15:32
*/
@Configuration
@Component
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 使用内存模式
clients.inMemory()
// 创建应用
.withClient("client_app1")
.secret("123456")
.redirectUris("http://localhost:8080/callback")
// 使用授权码模式
.authorizedGrantTypes("authorization_code")
// 读取用户信息
.scopes("read_userinfo", "read_contacts");
}
}
请求并访问
- 根据授权服务器的配置请求获取授权码:
http://localhost:8080/oauth/authorize?client_id=client_app1&redirect_uri=http://localhost:8080/callback&response_type=code&scope=read_userinfo - 请求会通过security认证管理器(输入用户名密码校验成功后)返回自定义的回调地址带上code码。注意此时的code码用来换令牌。
- 换取令牌请求
使用post提交
curl -X POST --user client_app1:123456 http://localhost:8080/oauth/token -H "content-type: application/x-www-form-urlencoded" -d "code=8uYpdo&grant_type=authorization_code&redirect_uri=http://localhost:8080/callback&scope=read_userinfo" - 返回得到access_token,就可以请求访问的资源。
二、简化模式
@Configuration
@Component
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 使用内存模式
clients.inMemory()
// 创建应用
.withClient("client_app1")
.secret("123456")
.redirectUris("http://localhost:8080/callback")
// 使用授权码模式 authorization_code
// 简化模式 implicit
// 密码模式 password
.authorizedGrantTypes("implicit")
// 过期时间
//.accessTokenValiditySeconds()
// 读取用户信息
.scopes("read_userinfo", "read_contacts");
}
}
三、密码模式
- 获取访问令牌
curl -X POST --user clientapp_1:123456 http://localhost:8080/oauth/token -H "accept: application/json" -H "content-type: application/x-www-form-urlencoded" -d "grant_type=password&username=admin&password=123456&scope=read_userinfo"