Implement Oauth server

Asked

Viewed 400 times

0

I would like to know how to implement an authentication server using Oauth.

If anyone has a clue how to do that, I’d appreciate it.

  • You want an implementation of preview Oauth, or of Consumer Oauth?

  • @Onosendai I need to authenticate my system with Oauth. Change my common authentication to Oauth

  • There are some ways to implement these settings. One of them is presented in this video. Take a look at the concept of Oauth and soon after watch this video that implements the same... https://www.youtube.com/watch?v=eKlQ1gFkZ5M

1 answer

1

class for implementation of the Oauth specification

public class OAuth
    {
        /// <summary>
        /// Configurando o OAuth
        /// </summary>
        public static void ConfigureOAuth(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                //Permite utilizar request sem HTTPS
                AllowInsecureHttp = true,
                //Local onde token sera gerado
                TokenEndpointPath = new PathString("/oauth/token"),
                //Tempo de expiração do token
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
                //Classe para autenticar seu serviço
                Provider = new AuthorizationServerProvider()
            });
        }
    }

 /// <summary>
/// Provider de autorizacao
/// </summary>
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    /// <summary>
    /// Método para validar o token no cache do Oauth
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        context.AdditionalResponseParameters.Add("Autorizo", context.Identity.Name);
        return Task.FromResult<object>(null);
    }

    /// <summary>
    /// Metodo para verificar as credencias de acesso
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        var container = new Container();
        Bindings.Start(container);
        var appUsuario = container.GetInstance<IRepositoryUsuario>();
        var appPerfil = container.GetInstance<IRepositoryPerfil>();
        var user = appUsuario.Autenticar(context.UserName, Criptografia.GetMd5Hash(context.Password));
        if (user != null)
        {              
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            //Adicionando nome do usuario no claim
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Nome));
            //adicionando a role do usuario
            identity.AddClaim(new Claim(ClaimTypes.Role, user.Perfil.Nome));
            GenericPrincipal principal = new GenericPrincipal(identity, appPerfil.FindAll().Select(role => role.Nome).ToArray());
            Thread.CurrentPrincipal = principal;
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "Usuario ou senha Inválidos");
        }
        return Task.FromResult<object>(null);
    }
}

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {             
            OAuth.ConfigureOAuth(app);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
    }

source code: https://github.com/EduardoSampaio/Projeto.Sistema.Vendas/tree/master/Sistema.Vendas.Service

Browser other questions tagged

You are not signed in. Login or sign up in order to post.