Spring Security 与 OAuth2(客户端)

作者: 聪明的奇瑞 | 来源:发表于2018-01-23 11:21 被阅读4783次

个人 OAuth2 全部文章

client(客户端) (改篇文章尚未修改,仅供参考)

  • OAuth2 客户端的实现方式没有太多任何规定,可自行编写登录逻辑
  • 也可使用 OAuth2 提供的 @EnableOAuth2Sso 注解实现单点登录,该注解会添加身份验证过滤器替我们完成所有操作,只需在配置文件里添加授权服务器和资源服务器的配置即可

添加配置

server:
  port: 8083
security:
  oauth2:
    sso:
      loginPath: /login   # 登录路径
    client:
      clientId: client
      clientSecret: secret
      userAuthorizationUri: http://localhost:8081/oauth/authorize
      access-token-uri: http://localhost:8081/oauth/token
    resource:
      userInfoUri: http://localhost:8082/user

添加 Security 配置,并启动 @EnableOAuthSso

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                // 禁用 CSRF 跨站伪造请求,便于测试
                csrf().disable()
                // 验证所有请求
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                //允许访问首页
                .antMatchers("/","/login").permitAll()
                .and()
                // 设置登出URL为 /logout
                .logout().logoutUrl("/logout").permitAll()
                .logoutSuccessUrl("/")
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

下面是测试用的控制类

@RestController
public class HelloController {

    @GetMapping("/")
    public String welcome() {
        return "welcome";
    }

}
  • 测试

访问 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. use server.context-path to move each App to different paths, note that you need to do this for both
2. 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

相关文章

网友评论

    本文标题:Spring Security 与 OAuth2(客户端)

    本文链接:https://www.haomeiwen.com/subject/jifsaxtx.html