【问题标题】:JWT authentication from Unity script来自 Unity 脚本的 JWT 身份验证
【发布时间】:2018-03-06 21:00:55
【问题描述】:

我正在尝试编写一个简单的 Unity 脚本,该脚本将使用 JWT 对我的服务器进行身份验证。不幸的是,我不能为 JWT 使用 .NET 插件,因为它需要比 Unity 使用的(Mono 的东西)更新版本的 .NET。所以我试着自己写。我可以设法执行登录,但之后我似乎无法弄清楚如何使用 idToken。这就是我所拥有的:

using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

public class JsonLoaderTest : MonoBehaviour
{
    public static string BASE_HTTP_URL = "http://localhost:8080/";
    public static string BASE_HTTPS_URL = "https://localhost:8080/";

    private string _idToken = "";

    // Use this for initialization
    [UsedImplicitly]
    IEnumerator Start () {
        yield return StartCoroutine(GetBeers());
        yield return StartCoroutine(Login());
        yield return StartCoroutine(GetBeers());
    }

    private IEnumerator GetBeers()
    {
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Authorization", "Bearer " + _idToken);
        WWW www = new WWW(BASE_HTTP_URL + "api/beers", null, headers);
        while (!www.isDone) yield return null;
        Debug.Log(www.text);
    }

    public class LoginPackage
    {
        public string username;
        public string password;
        public bool rememberMe;
    }

    public class IdTokenPackage
    {
        public string idToken;
    }

    private IEnumerator Login()
    {
        LoginPackage loginPackage = new LoginPackage();
        loginPackage.username =  "admin";
        loginPackage.password = "admin";
        loginPackage.rememberMe = true;

        Dictionary<string, string> postHeaders = new Dictionary<string, string>();
        postHeaders.Add("Content-Type", "application/json");
        string json = JsonUtility.ToJson(loginPackage);
        byte[] postData = System.Text.Encoding.UTF8.GetBytes(json);
        WWW www = new WWW(BASE_HTTP_URL + "api/authenticate", postData, postHeaders);
        while (!www.isDone) yield return null;
        Debug.Log(www.text);
        _idToken = JsonUtility.FromJson<IdTokenPackage>(www.text).idToken;
    }
}

正如您所料,第一个“GetBeers”请求失败并返回 401,因为我没有 ID 令牌。登录有效并返回一个 idToken,但是当我尝试使用非空 ID 发出第二个“GetBeers”请求时,它仍然失败并显示 401。这是服务器上的日志:

2017-09-25 21:32:39.904 DEBUG 9968 --- [ XNIO-2 task-16] c.s.beerapp.aop.logging.LoggingAspect    : Enter: org.springframework.boot.actuate.audit.AuditEventRepository.add() with argument[s] = [AuditEvent [timestamp=Mon Sep 25 21:32:39 CEST 2017, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]]
2017-09-25 21:32:39.907 DEBUG 9968 --- [ XNIO-2 task-16] c.s.beerapp.aop.logging.LoggingAspect    : Exit: org.springframework.boot.actuate.audit.AuditEventRepository.add() with result = null
2017-09-25 21:32:39.909 DEBUG 9968 --- [ XNIO-2 task-16] i.g.j.s.Http401UnauthorizedEntryPoint    : Pre-authenticated entry point called. Rejecting access
2017-09-25 21:32:40.145 DEBUG 9968 --- [ XNIO-2 task-25] c.s.beerapp.aop.logging.LoggingAspect    : Enter: com.svendhhh.beerapp.web.rest.UserJWTController.authorize() with argument[s] = [LoginVM{username='admin', rememberMe=true}, com.codahale.metrics.servlet.AbstractInstrumentedFilter$StatusExposingServletResponse@7f7712]
2017-09-25 21:32:40.146 DEBUG 9968 --- [ XNIO-2 task-25] c.s.b.security.DomainUserDetailsService  : Authenticating admin
Hibernate: select user0_.id as id1_7_0_, authority2_.name as name1_4_1_, user0_.created_by as created_2_7_0_, user0_.created_date as created_3_7_0_, user0_.last_modified_by as last_mod4_7_0_, user0_.last_modified_date as last_mod5_7_0_, user0_.activated as activate6_7_0_, user0_.activation_key as activati7_7_0_, user0_.email as email8_7_0_, user0_.first_name as first_na9_7_0_, user0_.image_url as image_u10_7_0_, user0_.lang_key as lang_ke11_7_0_, user0_.last_name as last_na12_7_0_, user0_.login as login13_7_0_, user0_.password_hash as passwor14_7_0_, user0_.reset_date as reset_d15_7_0_, user0_.reset_key as reset_k16_7_0_, authoritie1_.user_id as user_id1_8_0__, authoritie1_.authority_name as authorit2_8_0__ from jhi_user user0_ left outer join jhi_user_authority authoritie1_ on user0_.id=authoritie1_.user_id left outer join jhi_authority authority2_ on authoritie1_.authority_name=authority2_.name where user0_.login=?
2017-09-25 21:32:40.237 DEBUG 9968 --- [ XNIO-2 task-25] c.s.beerapp.aop.logging.LoggingAspect    : Enter: org.springframework.boot.actuate.audit.AuditEventRepository.add() with argument[s] = [AuditEvent [timestamp=Mon Sep 25 21:32:40 CEST 2017, principal=admin, type=AUTHENTICATION_SUCCESS, data={}]]
Hibernate: insert into jhi_persistent_audit_event (event_id, event_date, event_type, principal) values (null, ?, ?, ?)
2017-09-25 21:32:40.240 DEBUG 9968 --- [ XNIO-2 task-25] c.s.beerapp.aop.logging.LoggingAspect    : Exit: org.springframework.boot.actuate.audit.AuditEventRepository.add() with result = null
2017-09-25 21:32:40.242 DEBUG 9968 --- [ XNIO-2 task-25] c.s.beerapp.aop.logging.LoggingAspect    : Exit: com.svendhhh.beerapp.web.rest.UserJWTController.authorize() with result = <200 OK,com.svendhhh.beerapp.web.rest.UserJWTController$JWTToken@566d9495,{}>
2017-09-25 21:32:40.257 DEBUG 9968 --- [ XNIO-2 task-24] c.s.beerapp.aop.logging.LoggingAspect    : Enter: org.springframework.boot.actuate.audit.AuditEventRepository.add() with argument[s] = [AuditEvent [timestamp=Mon Sep 25 21:32:40 CEST 2017, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]]
2017-09-25 21:32:40.258 DEBUG 9968 --- [ XNIO-2 task-24] c.s.beerapp.aop.logging.LoggingAspect    : Exit: org.springframework.boot.actuate.audit.AuditEventRepository.add() with result = null
2017-09-25 21:32:40.260 DEBUG 9968 --- [ XNIO-2 task-24] i.g.j.s.Http401UnauthorizedEntryPoint    : Pre-authenticated entry point called. Rejecting access

谁能告诉我我做错了什么?我是否以错误的方式/格式包含身份验证标头?

【问题讨论】:

  • 哦,我现在可以看到问题在于我对返回的 JSON 的反序列化。我没有将id-token 值输出到我的IdTokenPackage 类的idToken 字段中......
  • ...但是,我不知道为什么不这样做。我想可能是因为我错过了[Serializable] 标签,但这并没有帮助......

标签: c# authentication unity3d jwt


【解决方案1】:

原来问题出在我的IdTokenPackage 类中的变量名。我已将 json 中的值读取为id-token,并假设这将被序列化为idToken(因为您不能在 c# 变量名中使用破折号)。但是,json中的实际名称是id_token,我不得不相应地更改C#类中的名称:

public class IdTokenPackage
{
    public string id_token;
}

这确实意味着我的问题与 JWT 不完全有关,但至少如果有人自己从 Unity 实施 JWT 身份验证,那么也许有人会发现该脚本很有用。

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 2012-10-21
    • 1970-01-01
    • 2018-03-25
    • 2015-01-08
    • 1970-01-01
    • 2021-01-31
    • 2023-01-22
    • 2020-03-18
    相关资源
    最近更新 更多