认证过程:客户端-->向授权服务进行认证-->授权服务返回给客户端一个token客户端拿着token去资源服务访问资源-->资源服务返回给客户端资源解决的是:用户和资源之间的关系
授权服务模式
1./oauth/authorize?client_id=client&response_type=code&redirect_uri=http://www.baidu.com&scopes=all 在授权码模式中获取code码通过code码访问/oauth/token获取token 在静默模式下将response_type设为token直接获取token
/oauth/token 在密码模式和客户端授权模式下直接访问获取token
授权码模式
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-cloud-starter-oauth2包含了 spring-cloud-starter-security-->
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<!--需要用到springsecurityOAth2用的事springCloud中的依赖所用需要配置下SpringCloudy-->
<dependencyManagement>
<dependencies>
<!--spring boot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--Spring cloud alibaba 新加-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
SecurityConfig
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//security配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successForwardUrl("/successLogin")
.failureForwardUrl("/failureHandlerLogin");
//授权
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/login/**", "oauth/**", "/logout/**").permitAll()
.antMatchers("/user/showLogin").permitAll()
.antMatchers("/user/test").hasAuthority("admin")
.anyRequest().authenticated();
http.csrf().disable();
}
//密码加密
@Bean
public PasswordEncoder getPs() {
return new BCryptPasswordEncoder();
}
}
授权服务配置
@Configuration
@EnableAuthorizationServer //开启身份认证服务
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
//设置oauth的token存储令牌方式
@Bean
public TokenStore tokenStore() {
//使用内存存储令牌(普通令牌)
return new InMemoryTokenStore();
}
/**
* authorization_code 授权码模式 需要拿到code 去换token
* password 密码模式
* implicit 静默授权 不需要code直接获取token
* client_credential 客户端授权
* refresh_token 自动刷新token
*/
//客户端服务
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()//前使用内存的方式存储 后续更改为数据库
.withClient("client") //设置客户端ID
.secret(new BCryptPasswordEncoder().encode("112233"))//设置第三方应用的密码
.scopes("read")//配置第三方应用的作用域
.authorizedGrantTypes("authorization_code")//授权模式
.accessTokenValiditySeconds(60)//设置token有效时间
.redirectUris("http://www.baidu.com");//授权后跳转的地址
}
//暴露授权服务配置
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)//暴露令牌存储给tokenStore
}
}
UserDetailsServiceImpl
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder pw;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (!username.equals("admin")){
throw new UsernameNotFoundException("账号不对");
}
String password=pw.encode("1234");
return new User(username,password,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin,abc"));
}
}
启动类
@SpringBootApplication
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)//开启注解 可以不使用
public class SpringSecurityaouth2Application {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityaouth2Application.class,args);
}
}
测试:1.访问:http://localhost:8080/oauth/authorize?client_id=client&response_type=code&redirect_uri=http://www.baidu.com&scopes=all
/oauth/authorize 获取code码
client_id 授权服务中设置的客户端id
response_type 响应类型
redirect_uri 重定向地址
scopes 授权范围
2.进行身份认证 在进行访问跳转到重定向地址https://www.baidu.com/?code=3F5U17 获取到code码
3.通过postman对/oauth/token发送post请求 Authorization中选择Basic Auth 输入客户端ID和秘钥进行验证;在参数中设置 grant_type:authorization_code
redirect_uri:http://www.baidu.com
code:3F5U17---在重定向地址获取到的code码
4.发送会获取到一个:{
"access_token": "c989d97b-60cf-42d6-a09c-8c159f5b7494", 获取到的token
"token_type": "bearer", token类型
"expires_in": 59, 剩余有效时长
"scope": "read" scope权限
}
静默授权
//客户端服务 只需要授权码授权改为静默授权
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()//前使用内存的方式存储 后续更改为数据库
.withClient("client") //设置客户端ID
.secret(new BCryptPasswordEncoder().encode("112233"))//设置第三方应用的密码
.scopes("read")//配置第三方应用的作用域
.authorizedGrantTypes("implicit")//授权模式
.accessTokenValiditySeconds(60)//设置token有效时间
.redirectUris("http://www.baidu.com");//授权后跳转的地址
}
访问:将response_type=code改为response_type=token
http://localhost:8080/oauth/authorize?client_id=client&response_type=token&redirect_uri=http://www.baidu.com&scopes=all
结果:https://www.baidu.com/#access_token=a6251bd4-585c-43bb-9710-df011047f419&token_type=bearer&expires_in=59&scope=read
密码模式
在授权模式的基础上进行更改
@Configuration
@EnableAuthorizationServer //开启授权服务
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder pw;
@Autowired
private UserDetailServiceImpl service; //用户
@Autowired
private AuthenticationManager authenticationManager;//认证管理器
@Autowired
private TokenStore tokenStore;
//设置oauth的token存储令牌方式
@Bean
public TokenStore tokenStore() {
//使用内存存储令牌(普通令牌)
return new InMemoryTokenStore();
}
//暴露授权服务端点
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)//暴露授权服务给认证管理器
.tokenStore(tokenStore)//暴露令牌存储给tokenStore
.userDetailsService(service);//暴露登录登录逻辑给自定义登录
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()//内存模式
.withClient("client")//客户端ID
.secret(pw.encode("112233"))//秘钥
.redirectUris("http://www.baidu.com")//重定向地址 重定向之后可以拿到授权码
.scopes("all")//授权范围 all全
//授权类型:authorization_code:授权码模式
.authorizedGrantTypes("authorization_code","password");
}
}
//在SecurityConfig中将AuthenticationManager(认证管理器)注入到Spring容器中
//因为使用密码授权不需要登录了 内部就需要一个认证管理器
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
测试:1.通过postman对/oauth/token发送post请求 Authorization中选择Basic Auth 输入客户端ID和秘钥进行验证;传入参数: grant_type:password
username:admin --用户账号
password:1234 --用户密码
2.发送会获取到一个:{
"access_token": "c989d97b-60cf-42d6-a09c-8c159f5b7494", 获取到的token
"token_type": "bearer", token类型
"expires_in": 59, 剩余有效时长
"scope": "read" scope权限
}
客户端授权模式
//客户端服务 直接修改授权模式就可以了
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()//前使用内存的方式存储 后续更改为数据库
.withClient("client") //设置客户端ID
.secret(new BCryptPasswordEncoder().encode("112233"))//设置第三方应用的密码
.scopes("read")//配置第三方应用的作用域
.authorizedGrantTypes("client_credentials")//授权模式
.accessTokenValiditySeconds(60)//设置token有效时间
.redirectUris("http://www.baidu.com");//授权后跳转的地址
}
1.通过postman对/oauth/token发送post请求 Authorization中选择Basic Auth 输入客户端ID和秘钥进行验证;传入参数: grant_type:client_credentials
2.发送会获取到一个:{
"access_token": "c989d97b-60cf-42d6-a09c-8c159f5b7494", 获取到的token
"token_type": "bearer", token类型
"expires_in": 59, 剩余有效时长
"scope": "read" scope权限
}
刷新令牌
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("112233"))
.scopes("all")
.authorizedGrantTypes("authorization_code","password","refresh_token")
.accessTokenValiditySeconds(60)
.refreshTokenValiditySeconds(2222)
.autoApprove(true)
.redirectUris("http://localhost:8081/login");
}
在进行获取就会发现获取到的东西多了个 refresh_token
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mjc5MDAwMDUsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iLCJhYmMiXSwianRpIjoiNzQ4NWM5NWQtOGYzNC00YzlhLTlhYTktOWJiYzc0MGI4Nzc4IiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsiYWxsIl19.ZNDsxuCdg60IWNiqZg2mXawa2LN2d_OBhIpRBTSsBUs",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJhdGkiOiI3NDg1Yzk1ZC04ZjM0LTRjOWEtOWFhOS05YmJjNzQwYjg3NzgiLCJleHAiOjE2Mjc5MDIxNjcsImF1dGhvcml0aWVzIjpbImFkbWluIiwiYWJjIl0sImp0aSI6ImJhM2JmNWNkLTU4NTAtNGZhOS1iNGI5LThhNzAwM2E4MmQzOSIsImNsaWVudF9pZCI6ImNsaWVudCJ9.MmfIbJaY8rns7nmYYOzgUMoH7NX_xDa1lgkEeHempJg",
"expires_in": 59,
"scope": "all",
"jti": "7485c95d-8f34-4c9a-9aa9-9bbc740b8778"}
如果过去后可以直接
grant_type:refresh_token
refresh_token: 以前请求给的refresh_token值 同样也需要设置Basic Auth 直接请求就会获取到新的access_token
整合jwt
@Configuration
@EnableAuthorizationServer //开启身份认证服务
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private UserDetailsServiceImpl service;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
/**
* authorization_code 授权码模式
* password 密码模式
* implicit 静默授权
* client_credentials 客户端授权
* refresh_token 自动刷新token
*/
//客户端服务
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()//前使用内存的方式存储 后续更改为数据库
.withClient("client") //设置客户端ID
.secret(new BCryptPasswordEncoder().encode("112233"))//设置第三方应用的密码
.scopes("read")//配置第三方应用的作用域
.authorizedGrantTypes("password")//授权模式 "password", "client_credentials", "refresh_token"
.accessTokenValiditySeconds(60)//设置token有效时间
.redirectUris("http://www.baidu.com");//授权后跳转的地址
}
//暴露授权服务给token的存储
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager) //将身份管理器暴露出来
.tokenStore(tokenStore)//将令牌存储方式暴露出来
.accessTokenConverter(jwtAccessTokenConverter)//将token转换器暴露出来
.userDetailsService(service);//将授权用户暴露出来
}
//设置oauth的token存储令牌方式
@Bean
public TokenStore tokenStore() {
//将令牌给jwt
return new JwtTokenStore(jwtAccessTokenConverter);
}
/**
设置jwt转换器
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("nihaoawoshimiyao");
return jwtAccessTokenConverter;
}
}
资源服务—-前后端分离使用
通过axios
auth: {username: 'janedoe', password: 's00pers3cret'},设置请求授权服务的Basic Auth
/**
* 整合jwt之后开启资源服务
* 通过继承ResourceServerConfigurerAdapter类 对jwt进行解析
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
/**
* 转换jwt
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("nihaoawoshimiyao");
return jwtAccessTokenConverter;
}
@Bean
public TokenStore tokenStore(){
return new JwtTokenStore(jwtAccessTokenConverter);
}
/**
* 这是资源服务配置 从tokenSrore中拿到token 进行解析
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore());
}
//这可以不重写 -- 可以通过注解配置权限
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/getPay").hasAuthority("admin")//根据token 判断是有权限 和security中相同
.antMatchers("/aa").access("#oauth2.hasScope('all')") //判断授权服务器的scopes作用域
.anyRequest().authenticated();
http.exceptionHandling().accessDeniedHandler(new DinasurHandler());
http.csrf().disable();
}
}
资源服务 一般都是单独出来一个模块:
访问资源服务的时候一般都通过
http://localhost:8002/getPay?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTU3OTEwNzEsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiMWY2Y2I5OWMtNGQyOC00Nzk4LWExMjEtOTA2ZTlhYjcwZGI1IiwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsicmVhZCJdfQ.XG0eLVvQ4yG7nzUKWIPxzm_kdpEHVGu2_lcv1-kR3hw
带着access_token=jwt令牌当参数访问
或者
通过设置请求头 Authorization:bearer token值 进行访问(多用)
资源服务和页面都在后端
授权服务
@Configuration
@EnableAuthorizationServer
public class SecurityOAuthConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
TokenStore tokenStore;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailServiceImpl userDetailService;
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("112233");
return jwtAccessTokenConverter;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("112233"))
.scopes("all")
.authorizedGrantTypes("authorization_code","password")//实际使用的是authorization_code
.accessTokenValiditySeconds(60)
.autoApprove(true)//自动授权
.redirectUris("http://localhost:8081/login");//必须重定向的是资源服务的login
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.userDetailsService(userDetailService);
}
//新增的否则资源服务器过不来 ---前后端分离的授权服务器不用
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//设置必须身份认证
security.tokenKeyAccess("isAuthenticated()");
}
}
//security配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin();
//授权
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/login/**", "/oauth/**", "/logout/**").permitAll()
.antMatchers("/user/showLogin").permitAll()
.antMatchers("/user/test").hasAuthority("admin")
.anyRequest().authenticated();
http.csrf().disable();
http.cors().disable();
}
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public PasswordEncoder password() {
return new BCryptPasswordEncoder();
}
}
资源服务
server:
port: 8081
servlet:
session:
cookie:
name: OAUTH2-CLIENT-SESSION2 #防止session冲突
#这就是资源服务的配置不需要其他配置
security:
oauth2:
client:
client-id: client #设置授权服务的clientid
client-secret: 112233 #设置授权服务的秘钥
user-authorization-uri: http://localhost:8080/oauth/authorize #设置的是获取code码的路径
access-token-uri: http://localhost:8080/oauth/token #获取token路径
scope: all
resource:
jwt:
key-uri: http://localhost:8080/oauth/token_key #设置请求jwt的路径
@SpringBootApplication
@EnableOAuth2Sso //开启单点登录
public class ResourceApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
}
访问路径会跑到授权服务区让进行登录 登录完后会跳转回来
