I would like to know how to implement an authentication server using OAuth.
If someone has a light how to do this, thank you.
I would like to know how to implement an authentication server using OAuth.
If someone has a light how to do this, thank you.
class for implementing 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: link