Spring Security OAuth2 SSO Несанкционированная ошибка 401 - PullRequest
0 голосов
/ 19 марта 2019

Я новичок в Spring Security и OAuth2 SSO в частности.

В настоящее время я пытаюсь протестировать и изучить этот учебник Spring Boot OAuth2: https://spring.io/guides/tutorials/spring-boot-oauth2/

Я могу войти, используя аналогичные настройки application.yml, например:

security:
 oauth2:
  client:
   clientId: 233668646673605
   clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
   accessTokenUri: https://graph.facebook.com/oauth/access_token
   userAuthorizationUri: https://www.facebook.com/dialog/oauth
   tokenName: oauth_token
   authenticationScheme: query
   clientAuthenticationScheme: form
resource:
  userInfoUri: https://graph.facebook.com/me

Вот мой pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sao.social.apps</groupId>
<artifactId>SocialApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SocialApplication</name>
<description>OAuth2 Login With Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
            <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.1.RELEASE</version>
            </dependency>
            <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.1</version>
    </dependency>
    <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.2.0</version>
    </dependency>
    <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>js-cookie</artifactId>
        <version>2.1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Вот основной класс, в котором также включен OAuth2SSO, а также контроллер безопасности и отдыха:

@SpringBootApplication
    @EnableOAuth2Sso
    @RestController
    public class SocialApplication extends WebSecurityConfigurerAdapter  {
    @RequestMapping("/user")
       public Principal user(Principal principal) {
       return principal;
      }
      @Override
      protected void configure(HttpSecurity httpSec) throws Exception{
         httpSec
         .antMatcher("/**")
         .authorizeRequests()
              .antMatchers("/", "/login**", "/webjars/**", "/error**")
              .permitAll()
         .anyRequest()
              .authenticated()
              .and().logout().logoutSuccessUrl("/").permitAll()
        .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
  }
   public static void main(String[] args) {
        SpringApplication.run(SocialApplication.class, args);
    }

}

И, наконец, вот представление: index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Demo</title>
    <meta name="description" content=""/>
    <meta name="viewport" content="width=device-width"/>
    <base href="/"/>
    <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <h1>Login</h1>
        <div class="container unauthenticated">
    With Facebook: <a href="/login">click here</a>
</div>
    <div class="container authenticated" style="display:none">
        Logged in as: <span id="user"></span>
    </div>
</div>

 <script type="text/javascript">
    $.get("/user", function(data) {
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide();
        $(".authenticated").show();
    });
</script>
</body>
</html>    

Моя основная проблема заключается в том, что я могу войти в систему с Facebook (в данном случае с сервером авторизации), но затем, когда я перенаправлен на localhost: 8080 / login, я всегда получаю 401 несанкционированную ошибку с весны вместо того, чтобы показывать мне имя пользователя, успешно прошедшего аутентификацию и вошедшего в систему, как и ожидалось, в view-index.html. Есть ли что-то еще, что мне нужно настроить на Facebook или я что-то упускаю в Spring?

Спасибо!

1 Ответ

0 голосов
/ 21 марта 2019

Убедитесь, что пакет класса SocialApplication находится на том же уровне, что и другие пакеты, возможно, аннотация @SpringBootApplication вашего основного класса не сканирует его компоненты.

Это решение для меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...