本文介绍了游戏的框架和离子移动,我需要安全无Cookie,但令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有使用移动应用程序,我在离子创建和后端的API,我$ C $光盘播放框架的一个问题,我的问题简单地说就是我需要的方式来处理安全问题,希望调用一个需要保护的API ,平均用户必须登录做动作,如例来宾可以查看组,但如果登录只能加入。

I have an issue with using mobile app that I created in Ionic and back-end APIs that I coded in play framework, my issue simply is I need way to handle security matter for calling APIs that need to be secured, mean user must be logged in to do actions, as example guest can view group but can join only if logged in.

我的问题,我相信,饼干不支持移动,我有code检查会话存储在饼干,其工作的网站,但它不会为移动工作的,对吧?

My issue that I believe that cookies is not supported for Mobile, i have code checking session that stored in cookies, its working for website, but it will not work for mobile, right?

目前我正在试图发送,在后台生成和登录响应中返回,并存储在localStorage的离子型中​​的标记,但我的问题是,我不能送令牌与要求进行验证。

Currently I'm trying to send a token that generated in back-end and returned with login response and stored in localStorage in Ionic, but my issue is that I can't sent token to be validated with request.

前端:
我有以下HTTP拦截器:

Front End:I have the following http interceptor :

  angular
    .module('app.core')
    .factory('sessionInjector', sessionInjector);

  /** @ngInject */
  function sessionInjector($q, sessionService, $rootScope) {
    return {
      request: function (config) {
        $rootScope.$broadcast('loading:show');
        if (!sessionService.isAnonymous())
          config.headers['x-session-token'] = sessionService.getToken();
        }
        return config;
      }
  }

后端:
控制器:

    @Security.Authenticated(Secure.class)
    public Result joinOrganization() {

       // Do some business

    }

Secure.java:

Secure.java :

@Override
public String getUsername(Http.Context ctx) {
    // Is this correct way? I get null here
    String str = ctx.request().getHeader("x-session-token");

    String userId = ctx.session().get("usedId");

    if (userId == null) {
        return null;
    }

    User user = Play.application().injector().instanceOf(UserService.class).findUserById(Integer.parseInt(userId));

    if (user != null && user.isActive) {
        return user.id;
    } else {
        return null;
    }
}


@Override
public Result onUnauthorized(Http.Context ctx) {
    return unauthorized(results);
}

注意:存储在数据库中标记:

Note: Tokens stored in database:

实体

@Entity
@Table(name = "AUTHTOKEN")
public class AuthToken extends BaseModel {

    @OneToOne(targetEntity = User.class, cascade = CascadeType.REFRESH, optional = false)
    public User user;

    @Column(nullable = false)
    public String token;

    @Column
    public long expiration;

    public AuthToken() {
    }

}

有关工作的饼干,但需要删除cookies和使用令牌,或者同时使用这些饼干的网站,令牌移动。

For cookies working, but need to remove cookies and use tokens, or use them together cookies for website, tokens for mobile .

推荐答案

我找到解决方案,它是复杂的,因为有很多开始的问题从的的的问题来自长的时间打开。

I found solution and it was complicated because there are many issues starting from that ngResource does not apply request interceptor its an issue opened from long time.

第二个问题是如何与 ngResource 发送令牌,它只是在这里添加标题的另一个问题动态获取的道理,这种动态的意思,因为的localStorage 在内存中迷路时刷新,所以你需要找回它,这可以用服务做的,和功能要求获得令牌,是这样的:

Second issue was how to send the token with ngResource, its simply with adding headers, the another issue here is getting dynamically the token, this "dynamically" means because the localStorage in memory getting lost when refresh so you need to get back it, this can be done with service, and function call for getting the token, something like this :

$resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, {
  charge: {method:'POST', params:{charge:true}, headers = {
        'x-session-token': function () {
          return sessionService.getToken()
        }}
 });

里面sessionService

// this to recreate the cache in memory once the user refresh, it will keep the data if exisit but will point to it again in memory
if (CacheFactory.get('profileCache') == undefined) {
  //if there is no cache already then create new one and assign it to profileCache
  CacheFactory.createCache('profileCache');
}

function getCurrentSession() {
  var profileCache = CacheFactory.get('profileCache');
  if (profileCache !== undefined && profileCache.get('Token') !== undefined) {
    return profileCache.get('Token');
  }
  return null;
}

function getToken() {
  var currentSession = getCurrentSession();
  if (currentSession != null && currentSession != '') {
    return currentSession.token;
  }
  return null;
}

和则此方法将内Secure.java工作

And then this method will work inside Secure.java

protected User getUser(Http.Context ctx) {
    String token = ctx.request().getHeader("x-session-token");

    if (token != null) {
        return securityService.validateToken(token);
    }
    return null;
}

这篇关于游戏的框架和离子移动,我需要安全无Cookie,但令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:19