在springboot中获取未经授权的错误?

mwngjboj  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(358)

这是我的问题。
我正在尝试使用springboot集成DexComRESTAPI以获取用户健康数据。
由DexComAPI使用oauth2流。
当我点击链接/登录时,应用程序重定向到dexcom api登录页面,并询问用户用户名和密码,如果身份验证成功,则dexcom登录页面通过发送带有此授权的授权代码重定向到我的应用程序重定向uri,我需要从dexcom获取访问令牌,之后我使用这是我的项目
我的问题是,在dexcom登录页面中成功输入用户名和密码后,它会被验证并重定向到我的应用程序,方法是提供如下授权代码,
http://localhost:8080/login?code=c956626ef691a1abe46bcc827a68ddfb&state=ljck1p 但是在同一个页面中,我在下面看到错误输入图像描述在这里输入白标签错误页面此应用程序没有/error的显式Map,因此您将此视为一种回退。
星期二6月8日20:52:24 ist 2021发生意外错误(类型=未授权,状态=401)。
我的代码

package com.example.mystorageapp;

 @RestController
 @EnableWebSecurity
 @EnableOAuth2Sso
public class Dexomapi extends WebSecurityConfigurerAdapter {

//@SuppressWarnings("deprecation")

@GetMapping(value="/login")
public Response get_auth(@RequestParam(value="code",required =false) String code, 
@RequestParam(value="state") String state ) throws IOException  {
RestTemplate ss=new RestTemplate();
    OkHttpClient client = new OkHttpClient();

    String client1= (String)"client_secret=t2sI8N7eY3dW50GK&
     client_id=XXXXXXXX&code="+code+"&grant_type=
      authorization_code&redirect_uri=http://localhost:8080/login";
        System.out.println(code);
        String data23="https://api.dexcom.com/v2/oauth2/token?"+client1;
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            ResponseEntity<String> response1
              = ss.getForEntity(data23  , String.class);
            ObjectMapper mapper3 = new ObjectMapper();
            JsonNode root = mapper3.readTree(response1.getBody());
            System.out.println(root);
            // Manually converting the response body InputStream to APOD using Jackson
            ObjectMapper mapper = new ObjectMapper();

            // Finally we have the response
            //System.out.println(apod.title);
            RequestBody body = RequestBody.create(mediaType,client1 );
            Request request = new Request.Builder()
              .url("https://api.dexcom.com/v2/oauth2/token")
              .post(body)
              .addHeader("content-type:", "application/x-www-form-urlencoded")
              .addHeader("cache-control", "no-cache")
              .build();
            ObjectMapper mapper1 = new ObjectMapper();
            Response response = client.newCall(request).execute();

             Map<String, Object> studentMap1 = mapper.convertValue(response, Map.class);
            System.out.println(studentMap1);
            return response;
    }
   @GetMapping("/")
     public String wow() {
    return "nice";
   }
   @Override
   public void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers(
          "/index.html","/error").permitAll().anyRequest().authenticated();
  }

  }

通过重定向,uri为/login
我的依赖

<?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 https://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.4.5</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>googleauth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dexcomapi</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
    <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.webjars</groupId>
        <artifactId>angularjs</artifactId>
        <version>1.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.2.0</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.webjars/webjars-locator -->
   <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>webjars-locator</artifactId>
   <version>0.40</version>
  </dependency>
  <dependency>
  <groupId>org.springframework.security.oauth</groupId>
  <artifactId>spring-security-oauth2</artifactId>
  <version>2.5.1.RELEASE</version>
</dependency>
 <dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>

</dependency>

</dependencies>

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

我的应用程序.yml

security:
        oauth2:
           client:
              clientId: Ncv8kRTLDnWM1oVeAuQRFFQugcBwIME2
              clientSecret: 2sI8N7eY3dW50GK
              accessTokenUri: https://api.dexcom.com/v2/oauth2/token
              userAuthorizationUri: https://api.dexcom.com/v2/oauth2/login
              tokenName: oauth_token
              authenticationScheme: header
              clientAuthenticationScheme: header
              scope: offline_access
          resource:
             userInfoUri: https://api.dexcom.com/v2/users/self/dataRange

我与angular js的前端代码

<body ng-app="app" ng-controller="home as home">
   <h1>Login</h1>
  <div class="container" ng-show="!home.authenticated">
    With Fitbit: <a href="/login">click here</a>
   </div>
   <div class="container" ng-show="home.authenticated">
    Logged in as: <span ng-bind="home.user"></span><br />
    Lifetime Steps: <span ng-bind="home.lifetimeSteps"></span><br />
    Lifetime Distance: <span ng-bind="home.lifetimeDistance"></span><br />
    Lifetime Floors: <span ng-bind="home.lifetimeFloors"></span><br />
   </div>
  <script type="text/javascript" src="/webjars/angularjs/angular.min.js"></script>
  <script type="text/javascript">
    angular.module("app", []).controller("home", function($http) {
        var self = this;

        $http.get("/login").success(function(data) {
            self.user = data.userAuthentication.details.user.fullName;
            self.authenticated = true;
        }).error(function() {
            self.user = "N/A";
            self.authenticated = false;
        });

        $http.get("/loginDexcom").success(function(data) {
            self.lifetimeSteps = data.steps.toLocaleString();
            self.lifetimeFloors = data.floors.toLocaleString();
            self.lifetimeDistance = data.distance.toLocaleString();
        }).error(function() {
            self.lifetimeSteps = "N/A";
        });
      });
    </script>
     </body>

谢谢你

iklwldmw

iklwldmw1#

通过将重定向uri显式设置为 http://localhost:8080/login ,您将覆盖默认的重定向uri,即 /login/oauth2/callback/{registrationId} .
此uri是特殊的,因为它提示 OAuth2LoginAuthenticationFilter 要处理该请求,请尝试对用户进行身份验证并创建 OAuth2AuthenticationToken .
当您将重定向uri设置为 /login 这个 OAuth2LoginAuthenticationFilter 未调用,并且应用程序不知道用户是否已通过身份验证,从而导致401。

相关问题