user3378283
user3378283

Reputation: 307

How to realize WebApi method that returns session id?

I would like to realize an authentification server with ASP.NET Identity for an mobile app. But I don't want to use default authentification methods. I would like to implement an WebApi method which creates session for user by login and password and returns the session id. So, in the mobile app I will add as an json parameter this session id for each request to the server.

Please give me an example how can I implement it? I have read this article http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/, but I also need an WebApi method to destroy the session, that is not possible as it described there.

Upvotes: 0

Views: 1044

Answers (1)

Belicosus
Belicosus

Reputation: 302

First of all: How would you make sure the session is "destroyed"? You can't be sure. The user could lose connection to the internet or hard shutdown his device.

Now, to answer your question.. kind of: What you need is a token that expires. This would make sure that the user is logged out after some time. You could do this by making a relatively short expiration time and then make sure this time i reset whenever the user uses the key to access the web service.

Taiseer's tutorial on Bit of Tech is excellent, for understanding the basics of Identity Framework and Token Based authentication.

Taiseer sets the Expiration time on his access tokens when he configures the OAuth in Startup.cs:

public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),  //<---- Right here
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }

You could do something like:

AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30)

Then you would have to find a way to refresh the token lifetime each time it is used. I don't have a suggestion for you at the moment, but maybe someone else does. You could do this by overriding the AuthorizeAttribute.

Taiseer also has a great guide on RefreshTokens which might come in handy: http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/

Upvotes: 1

Related Questions