client(客户端) (改篇文章尚未修改,仅供参考)
- OAuth2 客户端的实现方式没有太多任何规定,可自行编写登录逻辑
- 也可使用 OAuth2 提供的 @EnableOAuth2Sso 注解实现单点登录,该注解会添加身份验证过滤器替我们完成所有操作,只需在配置文件里添加授权服务器和资源服务器的配置即可
添加配置
1server: 2 port: 8083 3security: 4 oauth2: 5 sso: 6 loginPath: /login # 登录路径 7 client: 8 clientId: client 9 clientSecret: secret 10 userAuthorizationUri: http://localhost:8081/oauth/authorize 11 access-token-uri: http://localhost:8081/oauth/token 12 resource: 13 userInfoUri: http://localhost:8082/user
添加 Security 配置,并启动 @EnableOAuthSso
1@Configuration 2@EnableOAuth2Sso 3public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 4 5 @Override 6 protected void configure(HttpSecurity http) throws Exception { 7 http. 8 // 禁用 CSRF 跨站伪造请求,便于测试 9 csrf().disable() 10 // 验证所有请求 11 .authorizeRequests() 12 .anyRequest() 13 .authenticated() 14 //允许访问首页 15 .antMatchers("/","/login").permitAll() 16 .and() 17 // 设置登出URL为 /logout 18 .logout().logoutUrl("/logout").permitAll() 19 .logoutSuccessUrl("/") 20 .and() 21 .sessionManagement() 22 .sessionCreationPolicy(SessionCreationPolicy.STATELESS); 23 } 24} 25
下面是测试用的控制类
1@RestController 2public class HelloController { 3 4 @GetMapping("/") 5 public String welcome() { 6 return "welcome"; 7 } 8 9}
- 测试
访问 localhost:9007/login
但此时会出现 Authentication Failed: Could not obtain access token
- 上面问题我查找了下,以下是某网友给出的答复
Centinul as you've figured out this happens due to a cookie conflict, unfortunately cookies don't respect the port numbers. And so both Apps interfere with each other since both are setting JSESSIONID. There are two easy workarounds:
1 1. use server.context-path to move each App to different paths, note that you need to do this for both 22. set the server.session.cookie.name for one App to something different, e.g., APPSESSIONID
I would suggest to put this workaround in a profile that you activate for localhost only.
-
修改配置文件,添加以下内容
SESSION COOKIE 冲突
session: cookie: name: APPSESSIONID