Play framework and ionic for mobile I need Security without cookies but token

人盡茶涼 提交于 2019-12-11 13:50:10

问题


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.

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?

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.

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;
      }
  }

Back-End: Controller:

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

       // Do some business

    }

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:

@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() {
    }

}

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


回答1:


Mobile is no different to otherwise in regards of cookies. There are restrictions if AJAX, or cross-domain requests are used, and specially with Apple stuff, but they apply to non-mobile too. If your cookies work on a PC/Mac, they should do on a mobile device just as well. It's more of a form factor than anything else...




回答2:


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.

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()
        }}
 });

Inside 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;
}

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;
}


来源:https://stackoverflow.com/questions/36032237/play-framework-and-ionic-for-mobile-i-need-security-without-cookies-but-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!