我们在实现登录时,会在UI工程中,定义登录页面(login.html),然后在页面中输入自己的登陆账号,登陆密码,将请求提交给网关,然后网关将请求转发到auth工程,登陆成功和失败要返回json数据,在这个章节我们会按这个业务逐步进行实现
定义安全配置类修改SecurityConfig配置类,添加登录成功或失败的处理逻辑,例如:
package com.jt.auth.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**初始化密码加密对象*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**在这个方法中定义登录规则
* 1)对所有请求放行(当前工程只做认证)
* 2)登录成功信息的返回
* 3)登录失败信息的返回
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
//关闭跨域工具
http.csrf().disable();
//放行所有请求
http.authorizeRequests().anyRequest().permitAll();
//登录成功与失败的处理
http.formLogin()
.successHandler(successHandler())
.failureHandler(failureHandler());
}
@Bean
public AuthenticationSuccessHandler successHandler(){
// return new AuthenticationSuccessHandler() {
// @Override
// public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//
// }
// }
return (request,response,authentication) ->{
//1.构建map对象,封装响应数据
map<String,Object> map=new HashMap<>();
map.put("state",200);
map.put("message","login ok");
//2.将map对象写到客户端
writeJsonToClient(response,map);
};
}
@Bean
public AuthenticationFailureHandler failureHandler(){
return (request,response, e)-> {
//1.构建map对象,封装响应数据
Map<String,Object> map=new HashMap<>();
map.put("state",500);
map.put("message","login failure");
//2.将map对象写到客户端
writeJsonToClient(response,map);
};
}
private void writeJsonToClient(HttpServletResponse response,
Object object) throws IOException {
//1.将对象转换为json
//将对象转换为json有3种方案:
//1)Google的Gson-->toJson (需要自己找依赖)
//2)阿里的fastjson-->JSON (spring-cloud-starter-alibaba-sentinel)
//3)Springboot web自带的jackson-->writeValueAsString (spring-boot-starter-web)
//我们这里借助springboot工程中自带的jackson
//jackson中有一个对象类型为ObjectMapper,它内部提供了将对象转换为json的方法
//例如:
String jsonStr=new ObjectMapper().writeValueAsString(object);
//3.将json字符串写到客户端
PrintWriter writer = response.getWriter();
writer.println(jsonStr);
writer.flush();
}
}
定义用户信息处理对象
在spring security应用中底层会借助UserDetailService对象获取数据库信息,并进行封装,最后返回给认证管理器,完成认证操作,例如:
package com.jt.auth.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 登录时用户信息的获取和封装会在此对象进行实现,
* 在页面上点击登录按钮时,会调用这个对象的loadUserByUsername方法,
* 页面上输入的用户名会传给这个方法的参数
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
//UserDetails用户封装用户信息(认证和权限信息)
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//1.基于用户名查询用户信息(用户名,用户状态,密码,....)
//Userinfo userinfo=userMapper.selectUserByUsername(username);
String encodedPassword=passwordEncoder.encode("123456");
//2.查询用户权限信息(后面会访问数据库)
//这里先给几个假数据
List<GrantedAuthority> authorities =
AuthorityUtils.createAuthorityList(//这里的权限信息先这么写,后面讲
"sys:res:create", "sys:res:retrieve");
//3.对用户信息进行封装
return new User(username,encodedPassword,authorities);
}
}
网关中登陆路由配置
在网关配置文件中添加登录路由配置,例如
- id: router02
uri: lb://sca-auth #lb表示负载均衡,底层默认使用ribbon实现
predicates: #定义请求规则(请求需要按照此规则设计)
- Path=/auth/login/** #请求路径设计
filters:
- StripPrefix=1 #转发之前去掉path中第一层路径
基于Postman进行访问测试
启动sca-gateway,sca-auth服务,然后基于postman访问网关,执行登录测试,例如:
自定义登陆页面在sca-resource-ui工程的static目录中定义登陆页面,例如:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>login</title>
</head>
<body>
<div class="container"id="app">
<h3>Please Login</h3>
<form>
<div class="mb-3">
<label for="usernameId" class="form-label">Username</label>
<input type="text" v-model="username" class="form-control" id="usernameId" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="passwordId" class="form-label">Password</label>
<input type="password" v-model="password" class="form-control" id="passwordId">
</div>
<button type="button" @click="doLogin()" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vm=new Vue({
el:"#app",//定义监控点,vue底层会基于此监控点在内存中构建dom树
data:{ //此对象中定义页面上要操作的数据
username:"",
password:""
},
methods: {//此位置定义所有业务事件处理函数
doLogin() {
//1.定义url
let url = "http://localhost:9000/auth/login"
//2.定义参数
let params = new URLSearchParams()
params.append('username',this.username);
params.append('password',this.password);
//3.发送异步请求
axios.post(url, params).then((response) => {
debugger
let result=response.data;
console.log(result);
if (result.state == 200) {
alert("login ok");
} else {
alert(result.message);
}
})
}
}
});
</script>
</body>
</html>
启动sca-resource-ui服务后,进入登陆页面,输入用户名jack,密码123456进行登陆测试。
颁发登陆成功令牌构建令牌配置对象本次我们借助JWT(Json Web Token-是一种json格式)方式将用户相关信息进行组织和加密,并作为响应令牌(Token),从服务端响应到客户端,客户端接收到这个JWT令牌之后,将其保存在客户端(例如localStorage),然后携带令牌访问资源服务器,资源服务器获取并解析令牌的合法性,基于解析结果判定是否允许用户访问资源.
package com.jt.auth.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 {
//定义签名key,在执行令牌签名需要这个key,可以自己指定.
private String SIGNING_KEY = "auth";
//定义令牌生成策略.
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
//定义Jwt转换器,负责生成jwt令牌,解析令牌内容
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
//设置加密/解密口令
converter.setSigningKey(SIGNING_KEY);
return converter;
}
}
定义认证授权核心配置
第一步:在SecurityConfig中添加如下方法(创建认证管理器对象,后面授权服务器会用到):
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
第二步:所有零件准备好了开始拼装最后的主体部分,这个主体部分就是授权服务器的核心配置
package com.jt.auth.config;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
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.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.Arrays;
/**
* 完成所有配置的组装,在这个配置类中完成认证授权,JWT令牌签发等配置操作
* 1)SpringSecurity (安全认证和授权)
* 2)TokenConfig
* 3)Oauth2(暂时不说)
*/
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer //开启认证和授权服务
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
//此对象负责完成认证管理
private AuthenticationManager authenticationManager;
//TokenStore负责完成令牌创建,信息读取
private TokenStore tokenStore;
//JWT令牌转换器(基于用户信息构建令牌,解析令牌)
private JwtAccessTokenConverter jwtAccessTokenConverter;
//密码加密匹配器对象
private PasswordEncoder passwordEncoder;
//负责获取用户信息信息
private UserDetailsService userDetailsService;
//设置认证端点的配置(/oauth/token),客户端通过这个路径获取JWT令牌
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
//配置认证管理器
.authenticationManager(authenticationManager)
//验证用户的方法获得用户详情
.userDetailsService(userDetailsService)
//要求提交认证使用post请求方式,提高安全性
.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)
//要配置令牌的生成,由于令牌生成比较复杂,下面有方法实现
.tokenServices(tokenService());//这个不配置,默认令牌为UUID.randomUUID().toString()
}
//定义令牌生成策略
@Bean
public AuthorizationServerTokenServices tokenService(){
//这个方法的目标就是获得一个令牌生成器
DefaultTokenServices services=new DefaultTokenServices();
//支持令牌刷新策略(令牌有过期时间)
services.setSupportRefreshToken(true);
//设置令牌生成策略(tokenStore在TokenConfig配置了,本次我们应用JWT-定义了一种令牌格式)
services.setTokenStore(tokenStore);
//设置令牌增强(允许设置令牌生成策略,默认是非jwt方式,现在设置为jwt方式,并在令牌Payload部分允许添加扩展数据,例如用户权限信息)
TokenEnhancerChain chain=new TokenEnhancerChain();
chain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
services.setTokenEnhancer(chain);
//设置令牌有效期
services.setAccessTokenValiditySeconds(3600);//1小时
//刷新令牌应用场景:一般在用户登录系统后,令牌快过期时,系统自动帮助用户刷新令牌,提高用户的体验感
services.setRefreshTokenValiditySeconds(3600*72);//3天
return services;
}
//设置客户端详情类似于用户详情
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
//客户端id (客户端访问时需要这个id)
.withClient("gateway-client")
//客户端秘钥(客户端访问时需要携带这个密钥)
.secret(passwordEncoder.encode("123456"))
//设置权限
.scopes("all")//all只是个名字而已和写abc效果相同
//允许客户端进行的操作 这里的认证方式表示密码方式,里面的字符串千万不能写错
.authorizedGrantTypes("password","refresh_token");
}
// 认证成功后的安全约束配置,对指定资源的访问放行,我们登录时需要访问/oauth/token,需要对这样的url进行放行
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//认证通过后,允许客户端进行哪些操作
security
//公开oauth/token_key端点
.tokenKeyAccess("permitAll()")
//公开oauth/check_token端点
.checkTokenAccess("permitAll()")
//允许提交请求进行认证(申请令牌)
.allowFormAuthenticationForClients();
}
}
配置网关认证的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);
})
}
资源服务器配置添加依赖
打开资源服务的pom.xml文件,添加oauth2依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
令牌处理器配置
package com.jt.auth.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;
/**
* 创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.
* JWT令牌的构成有三部分构成:
* 1)HEADER (头部信息:令牌类型,签名算法)
* 2)PAYLOAD (数据信息-用户信息,权限信息,令牌失效时间,...)
* 3)SIGNATURE (签名信息-对header和payload部分进行加密签名)
*/
@Configuration
public class TokenConfig {
//定义令牌签发口令(暗号),这个口令自己定义即可
//在对header和PAYLOAD部分进行签名时,需要的一个口令
private String SIGNING_KEY= "auth";
//初始化令牌生成策略(默认生成策略 UUID)
//这里我们采用JWT方式生成令牌
@Bean
public TokenStore tokenStore(){
return new JwtTokenStore(jwtAccessTokenConverter());
}
//构建JWT令牌转换器对象,基于此对象创建令牌,解析令牌
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
converter.setSigningKey(SIGNING_KEY);
return converter;
}
}
资源服务令牌解析配置
package com.jt.resource.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
/**
* token服务配置
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}
/**
* 路由安全认证配置
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler());
http.authorizeRequests().anyRequest().permitAll();
}
//没有权限时执行此处理器方法
public AccessDeniedHandler accessDeniedHandler() {
return (request, response, e) -> {
Map<String, Object> map = new HashMap<>();
map.put("state", HttpServletResponse.SC_FORBIDDEN);//SC_FORBIDDEN的值是403
map.put("message", "没有访问权限,请联系管理员");
//1设置响应数据的编码
response.setCharacterEncoding("utf-8");
//2告诉浏览器响应数据的内容类型以及编码
response.setContentType("application/json;charset=utf-8");
//3获取输出流对象
PrintWriter out=response.getWriter();
//4 输出数据
String result=
new ObjectMapper().writeValueAsString(map);
out.println(result);
out.flush();
};
}
}
资源服务令牌解析配置
package com.jt.resource.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
/**
* token服务配置
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}
/**
* 路由安全认证配置
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler());
http.authorizeRequests().anyRequest().permitAll();
}
//没有权限时执行此处理器方法
public AccessDeniedHandler accessDeniedHandler() {
return (request, response, e) -> {
Map<String, Object> map = new HashMap<>();
map.put("state", HttpServletResponse.SC_FORBIDDEN);//SC_FORBIDDEN的值是403
map.put("message", "没有访问权限,请联系管理员");
//1设置响应数据的编码
response.setCharacterEncoding("utf-8");
//2告诉浏览器响应数据的内容类型以及编码
response.setContentType("application/json;charset=utf-8");
//3获取输出流对象
PrintWriter out=response.getWriter();
//4 输出数据
String result=
new ObjectMapper().writeValueAsString(map);
out.println(result);
out.flush();
};
}
}
ResourceController 方法配置
在controller的上传方法上添加 @PreAuthorize(“hasAuthority(‘sys:res:create’)”)注解,用于告诉底层框架方法此方法需要具备的权限,例如
@PreAuthorize("hasAuthority('sys:res:create')")
@PostMapping("/upload/")
public String uploadFile(MultipartFile uploadFile) throws IOException {
...
}
启动服务访问测试
- 第一步:启动服务(sca-auth,sca-resource-gateway,sca-resource)
- 第二步:执行登陆获取access_token令牌
- 第三步:携带令牌访问资源(url中的前缀"sca"是在资源服务器中自己指定的,你的网关怎么配置的,你就怎么写)
设置请求头(header),要携带令牌并指定请求的内容类型,例如