单点登录失败解决措施 单点登录框架有哪些( 四 )


第二步:检测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.定义urllet 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="https://www.520longzhigu.com/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部分进行加密签名) */@Configurationpublic class TokenConfig {//定义令牌签发口令(暗号),这个口令自己定义即可//在对header和PAYLOAD部分进行签名时,需要的一个口令private String SIGNING_KEY= "auth";//初始化令牌生成策略(默认生成策略 UUID)//这里我们采用JWT方式生成令牌@Beanpublic TokenStore tokenStore(){return new JwtTokenStore(jwtAccessTokenConverter());}//构建JWT令牌转换器对象,基于此对象创建令牌,解析令牌@Beanpublic 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 {@Autowiredprivate TokenStore tokenStore;/*** token服务配置*/@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenStore(tokenStore);}/*** 路由安全认证配置*/@Overridepublic 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的值是403map.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 {@Autowiredprivate TokenStore tokenStore;/*** token服务配置*/@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenStore(tokenStore);}/*** 路由安全认证配置*/@Overridepublic 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的值是403map.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’)”)注解,用于告诉底层框架方法此方法需要具备的权限,例如


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: