Security Authentication in Asp. Net MVC 4 Web API-use OAuth and mvcoauth

Source: Internet
Author: User
Tags http authentication oauth

Security Authentication in Asp. Net MVC 4 Web API-use OAuth and mvcoauth


Oauth authentication in various languages: http://oauth.net/code/

 

The previous article introduced how to use basic http authentication to implement cross-platform security authentication for asp.net web APIs. The following describes how to use oauth for authentication. Oauth may be familiar to everyone. Note that we are using a good open-source oauth library on the. net platform. DOTNETOPENAUTH.

As shown in, we need an ISSSUE Server to give us a token, and then go to the resource Server to request resources, that is, the Web API Server.


 

First, on the oAuthIssuer server, we need to implement a DotNetOpenAuth interface: IAuthorizationServer


 

Implementation of interfaces:

 

public class OAuth2Issuer : IAuthorizationServer
    {
        private readonly IssuerConfiguration _configuration;

        public OAuth2Issuer(IssuerConfiguration configuration)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            _configuration = configuration;
        }

        public RSACryptoServiceProvider AccessTokenSigningKey
        {
            get
            {
                return (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey;
            }
        }

        public DotNetOpenAuth.Messaging.Bindings.ICryptoKeyStore CryptoKeyStore
        {
            get { throw new NotImplementedException(); }
        }

        public TimeSpan GetAccessTokenLifetime(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage)
        {
            return _configuration.TokenLifetime;
        }

        public IClientDescription GetClient(string clientIdentifier)
        {
            const string secretPassword = "test1243";
            return new ClientDescription(secretPassword, new Uri("http://localhost/"), ClientType.Confidential);
        }

        public RSACryptoServiceProvider GetResourceServerEncryptionKey(DotNetOpenAuth.OAuth2.Messages.IAccessTokenRequest accessTokenRequestMessage)
        {
            return (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key;

        }

        public bool IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription authorization)
        {
            
            //claims added to the token
            authorization.Scope.Add("adminstrator");
            authorization.Scope.Add("poweruser");
            
            return true;
        }

        public bool IsResourceOwnerCredentialValid(string userName, string password)
        {
            return true;
        }

        public DotNetOpenAuth.Messaging.Bindings.INonceStore VerificationCodeNonceStore
        {
            get
            {
                throw new NotImplementedException();
            }
        }
    }

 

 

 

 

On the Web API Server, we need to use Http Message Handler to obtain httprequest information and determine whether authorization is available.

 

 public class OAuth2Handler : DelegatingHandler
    {
        private readonly ResourceServerConfiguration _configuration;

        public OAuth2Handler(ResourceServerConfiguration configuration)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            _configuration = configuration;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpContextBase httpContext;
            string userName;
            HashSet<string> scope;

            if (!request.TryGetHttpContext(out httpContext))
                throw new InvalidOperationException("HttpContext must not be null.");

            var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(
                                                        (RSACryptoServiceProvider)_configuration.IssuerSigningCertificate.PublicKey.Key,
                                                        (RSACryptoServiceProvider)_configuration.EncryptionVerificationCertificate.PrivateKey));

            var error = resourceServer.VerifyAccess(httpContext.Request, out userName, out scope);

            if (error != null)
                return Task<HttpResponseMessage>.Factory.StartNew(error.ToHttpResponseMessage);
            
            var identity = new ClaimsIdentity(scope.Select(s => new Claim(s, s)));
            if (!string.IsNullOrEmpty(userName))
                identity.Claims.Add(new Claim(ClaimTypes.Name, userName));
            
            httpContext.User = ClaimsPrincipal.CreateFromIdentity(identity);
            Thread.CurrentPrincipal = httpContext.User;

            return base.SendAsync(request, cancellationToken);
        }

    }

 

 

 

 

 

The ResourceServerConfiguration here uses the encrypted certificate.


 

Client call code:


 

You must obtain the Token from the IssueServer before calling the API to obtain data.

GetAccessToken:

 

 


 

Take a look at the Token information:

{"Access_token": "gAAAAIoUBVBrZ5jAxe5XeTgnJ8mGwwKsCReknueg4gLGlDQ77lR1yPfxt0yNfWLCBT7hxnHjRjuEwDTJ3J1YAnqML4MIgQg8A2cz2bs0EnxvCMfKnayKEesRM-lxLTFbWMpSxe2Xvjm61IbaXjrMkYDRMnV4Do8-7132tiOLIv02WOGlJAEAAIAAAACJ8F3SsE6cTI1XsioW_xOxHeESDzG16y01Gxm3HikYFUC3XIdekpPw0yMB4tavPmUj-kRyC1halbUX7JKf-Dihm6Ou5mexe9lcYTr9or_kH7WcDN5ZCryUK3OaecvwwjQVr5o9XD2ZyZSNDCNhVRFc5ypvP85zZCBW1KJkP3OTCV4AkMN-ROvgI8jxutYdsLLN-YbB7Ot5iypzWWbW0QxiwOzMEqG9nVtPwnIWOUMOvW5KbiELELhgjap60mwHzGrHG4TtA4jrNy8S9zjixO_q-FrgpAuC06CkSH-R4w9yPCLLDc9m3UoAnknFjd4PUbWLxCvlBpEK2sg03ENa0EOKzc2O5fEic9P-BiYt6afMwTgLkJlGBBjmCBpGZMkfLTw", "token_type": "bearer", "expires_in": "300", "scope": "http: \/localhost \/adminstrator poweruser "}


 

Client call:

 


 

Code:

 

 

Http://pan.baidu.com/s/1ntkMbCt

 

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.