首页 > 解决方案 > How to get oauth Authorization code in asp.net

问题描述

I am busy implementing an oauth Authorization Server on my ASP.NET WEB API.

I have setup the API to support authorization server:

Startup.Auth.cs

public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(IdentityDbContext.Create);           
        app.CreatePerOwinContext<UserManager>(UserManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";

        OAuthOptions = new OAuthAuthorizationServerOptions
        {  
            AllowInsecureHttp = true,
            ApplicationCanDisplayErrors = true,
            TokenEndpointPath = new PathString("/Token"),
            Provider = new SimpleAuthorizationServerProvider(),
            RefreshTokenProvider = new SimpleRefreshTokenProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
            AuthorizationCodeProvider = new SimpleAuthorizationCodeProvider()
        };

        app.UseOAuthBearerTokens(OAuthOptions);
        app.UseOAuthAuthorizationServer(OAuthOptions);
    }

I have then implemented my SimpleAuthorizationCodeProvider():

public class SimpleAuthorizationCodeProvider : IAuthenticationTokenProvider
{            

    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        context.Ticket.Properties.Dictionary.TryGetValue("as:client_id", out string clientId);

        //Build holder object
        var holder = new AuthorizationCodeHolder(0, clientId, context.SerializeTicket());

        var protectedTicket = AesSymmetricalEncryption.EncryptData(Key, JsonConvert.SerializeObject(holder));
        //Set the Token for the request
        context.SetToken(protectedTicket);
    }


    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        //Decrypt token
        var token = AesSymmetricalEncryption.DecyptData(Key, context.Token);
        //Convert back to object
        var ticket = JsonConvert.DeserializeObject<AuthorizationCodeHolder>(token);            
        //
        context.DeserializeTicket(ticket.Ticket);
    }

However, now my issue is, I do not know how to generate this authorization code?

I have a section on a separate MVC site, where a user logs in. After they have done that, I need to return a response with a parameter code={auth code}. How do I go about generating this authorization code?

Do I need to login to the api, and then call a specific endpoint? or can I just use the owin authentication in the MVC site to generate it?

I have tested the api, and I can login using an authentication code, but I just do not know how to generate a valid one?

标签: asp.net.netoauthasp.net-web-api2asp.net-identity-2

解决方案


推荐阅读