Spring Security 与 OAuth2程序员SpringBoot极简教程 · Spring Boot

Spring Security 与 OAuth2(客户端)

2018-01-23  本文已影响4783人  聪明的奇瑞

个人 OAuth2 全部文章

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

添加配置

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
上一篇 下一篇

猜你喜欢

热点阅读