目前的登陆操作,也就是用户的认证操作,其实现主要基于Spring Security框架,其认证简易流程如下:
颁发登陆成功令牌构建令牌配置对象
本次我们借助JWT(Json Web Token-是一种json格式)方式将用户相关信息进行组织和加密,并作为响应令牌(Token),从服务端响应到客户端,客户端接收到这个JWT令牌之后,将其保存在客户端(例如localStorage),然后携带令牌访问资源服务器,资源服务器获取并解析令牌的合法性,基于解析结果判定是否允许用户访问资源.
package com.cy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
public class TokenConfig {
@Bean
public TokenStore tokenStore(){
//这里采用JWT方式生成和存储令牌信息
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
//JWT令牌构成:header(签名算法,令牌类型),payload(数据部分),Signing(签名)
//这里的签名可以简单理解为加密,加密时会使用header中的算法以及我们自己提供的密钥,
//这里加密的目的是为了防止令牌被篡改。(这里的密钥要保存好,要存储在服务端)
jwtAccessTokenConverter.setSigningKey(SINGING_kEY);//设置密钥
return jwtAccessTokenConverter;
}
private static final String SINGING_kEY="auth";
}
定义认证授权核心配置
第一步:在SecurityConfig中添加如下方法(创建认证管理器对象,后面授权服务器会用到):
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
第二步:所有零件准备好了开始拼装最后的主体部分,这个主体部分就是授权服务器的核心配置
package com.cy.config;
import com.cy.service.UserDetailsServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.Arrays;
@AllArgsConstructor //生成全参的构造函数
@Configuration
@EnableAuthorizationServer //启动认证和授权服务
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
private AuthenticationManager authenticationManager;
private UserDetailsServiceImpl userDetailsService;
private TokenStore tokenStore;
private BCryptPasswordEncoder passwordEncoder;
private JwtAccessTokenConverter jwtAccessTokenConverter;
// public Oauth2Config(AuthenticationManager authenticationManager, UserDetailsServiceImpl userDetailsService, TokenStore tokenStore, BCryptPasswordEncoder passwordEncoder, JwtAccessTokenConverter jwtAccessTokenConverter) {
// this.authenticationManager = authenticationManager;
// this.userDetailsService = userDetailsService;
// this.tokenStore = tokenStore;
// this.passwordEncoder = passwordEncoder;
// this.jwtAccessTokenConverter = jwtAccessTokenConverter;
// }
//super.configure(endpoints);
//由谁完成认证?
//谁负责访问数据库?(认证时需要两部分信息:一部分来自客户端,一部分来自数据库)
//支持对什么请求进行认证(默认只支持post方式)
//认证成功以后令牌如何生成和存储(默认令牌生成UUID.randomUUID(),并且存储在方式是内存)
public void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception{
endpoints
//配置认证管理器
.authenticationManager(authenticationManager)
//验证用户的方法获得用户详情
.userDetailsService(userDetailsService)
//要求提交认证使用post请求方式,提高安全性
.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)
//配置令牌的生成
.tokenServices(tokenService());//这个不配置,默认令牌为UUID.randomUUID.toString
}
//系统底层在完成认证以后会调用TokenService对象的相关方法
//获取TokenStore,基于tokenStore获取token
@Bean
public AuthorizationServerTokenServices tokenService (){
//1.构建TokenService对象(此对象提供了创建,获取,刷新token的方法)
DefaultTokenServices services = new DefaultTokenServices();
//2.设置令牌生成和存储策略
services.setTokenStore(tokenStore);
//3.设置是否支持令牌刷新(访问令牌过期了,是否支持通过令牌刷新机制,延长令牌有效期)
services.setSupportRefreshToken(true);
//4.设置令牌增强(默认令牌比较简单,没有业务数据,
// 就是简单的随机字符串,但是现在希望使用jwt方式)
TokenEnhancerChain chain = new TokenEnhancerChain();
chain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
services.setTokenEnhancer(chain);
//5.设置访问令牌有效期
services.setAccessTokenValiditySeconds(3600);
//6.设置刷新令牌有效期
services.setRefreshTokenValiditySeconds(3600*72);
return services;
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//super.configure(security);
security
//1.定义(公开)要认证的url(permitAll())是官方定义好的
//公开oauth/token_key端点
.tokenKeyAccess("permitAll()")
//2.定义(公开)令牌检查的url
//公开oauth/token_key端点
.checkTokenAccess("permitAll()")
//3.允许客户端直接通过表单form方式提交认证
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//super.configure(clients);
clients.inMemory()
//定义客户端的id(客户端提交用户信息进行认证时需要这个id)
.withClient("gateway-client")
//定义客户端密钥(客户端提交用户信息时需要携带这个密钥)
.secret(passwordEncoder.encode("123456"))
//定义作用范围(所有符合规则的客户端)
.scopes("all")
//运行客户端基于密码方式,刷新令牌方式实现认证
.authorizedGrantTypes("password","refresh_token");
}
}
配置网关认证的URL
- id: router02
uri: lb://sca-auth
predicates:
#- Path=/auth/login/** #没要令牌之前,以前是这样配置
- Path=/auth/oauth/** #微服务架构下,需要令牌,现在要这样配置
filters:
- StripPrefix=1
Postman访问测试
第一步:启动服务
依次启动sca-auth服务,sca-resource-gateway服务。
第二步:检测sca-auth服务控制台的Endpoints信息,例如:
第三步:打开postman进行登陆访问测试
登陆成功会在控制台显示令牌信息,例如:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mjk5OTg0NjAsInVzZXJfbmFtZSI6ImphY2siLCJhdXRob3JpdGllcyI6WyJzeXM6cmVzOmNyZWF0ZSIsInN5czpyZXM6cmV0cmlldmUiXSwianRpIjoiYWQ3ZDk1ODYtMjUwYS00M2M4LWI0ODYtNjIyYjJmY2UzMDNiIiwiY2xpZW50X2lkIjoiZ2F0ZXdheS1jbGllbnQiLCJzY29wZSI6WyJhbGwiXX0.-Zcmxwh0pz3GTKdktpr4FknFB1v23w-E501y7TZmLg4",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqYWNrIiwic2NvcGUiOlsiYWxsIl0sImF0aSI6ImFkN2Q5NTg2LTI1MGEtNDNjOC1iNDg2LTYyMmIyZmNlMzAzYiIsImV4cCI6MTYzMDI1NDA2MCwiYXV0aG9yaXRpZXMiOlsic3lzOnJlczpjcmVhdGUiLCJzeXM6cmVzOnJldHJpZXZlIl0sImp0aSI6IjIyOTdjMTg2LWM4MDktNDZiZi1iNmMxLWFiYWExY2ExZjQ1ZiIsImNsaWVudF9pZCI6ImdhdGV3YXktY2xpZW50In0.1Bf5IazROtFFJu31Qv3rWAVEtFC1NHWU1z_DsgcnSX0",
"expires_in": 3599,
"scope": "all",
"jti": "ad7d9586-250a-43c8-b486-622b2fce303b"
}
登陆页面登陆方法设计
登陆成功以后,将token存储到localStorage中,修改登录页面的doLogin方法,例如
doLogin() {
//1.定义url
let url = "http://localhost:9000/auth/oauth/token"
//2.定义参数
let params = new URLSearchParams()
params.append('username',this.username);
params.append('password',this.password);
params.append("client_id","gateway-client");
params.append("client_secret","123456");
params.append("grant_type","password");
//3.发送异步请求
axios.post(url, params).then((response) => {
alert("login ok");
let result=response.data;
localStorage.setItem("accessToken",result.access_token);
location.href="/fileupload.html";
}).catch((error)=>{
console.log(error);
})
}



