【问题标题】:Authenticate MVC Contoller Using Bearer Token and redirect to the Controller [closed]使用承载令牌验证 MVC 控制器并重定向到控制器 [关闭]
【发布时间】:2019-03-25 02:49:59
【问题描述】:

我已经创建了一个 MVC 控制器,请找到下面的代码

现在我需要使用 OAuth 进行创建

我在 Azure 中创建了客户端 ID、客户端密码、资源和密钥, 并使用它我可以获得承载令牌

现在任何人都可以帮助我在我的 MVC 控制器中进行身份验证并使用 c# 重定向到 bankCreationController

public class BankCreationController : ApiController
{
    [HttpPost]
    [Route("~/BankCreationController ")]
    public string BankCreationController (sting s)
    {
    }
}

【问题讨论】:

  • 身份验证使用 ASP.NET 的身份验证系统发生,该系统在控制器之前运行。使用[Authorize] 属性并在Startup.cs 中设置身份验证和授权管道。这是 ASP.NET MVC 还是 ASP.NET Core?如果是核心,是核心 1 还是核心 2? AuthX 系统在 Core 2 中发生了重大变化。

标签: c# model-view-controller


【解决方案1】:

我有机会使用 .Net MVC 5 设置承载身份验证,这是我使用自定义属性设置它的方法。我认为我们需要进行一些定制以使其适用于 .Net Core

这个api需要有一个注解,在这个例子中我将它命名为BearerAuthentication,这样它就会在到达BankCreationMethod方法内部之前检查请求的header进行承载认证

[HttpPost]
[BearerAuthentication]
[Route("someurl")]
public string BankCreationMethod(string s){
}

然后创建一个自定义属性类名 BearerAuthentication,继承自 ActionFilterAttribute。对带有注释 [BearerAuthentication] 的操作的每个请求都将通过此方法 OnActionExecuting 进行检查。如果请求的header是Bearer类型并且有一个有效的token,这将返回一个有效的结果,否则将是一个HttpStatusCode.Unauthorized响应的动作。

public class BearerAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {

        // 1. Look for credentials in the request.
        HttpRequestMessage request = context.Request;
        AuthenticationHeaderValue authorization = request.Headers.Authorization;

        // 2. If there are no credentials, do nothing.
        if (authorization == null)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        // 3. If there are credentials but the filter does not recognize the 
        //    authentication scheme, do nothing.
        if (authorization.Scheme != "Bearer")
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        if (String.IsNullOrEmpty(authorization.Parameter))
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        //4.If there are credentials that the filter understands, try to validate them.          
        if (!String.IsNullOrEmpty(authorization.Parameter))
        {
            var apiKey = string.Empty;               
            if (!TokenService.IsValidToken(authorization.Parameter))
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }

            return;
        }

    }
}

检查请求中的令牌是否有效的服务以及加密令牌的算法可以使用 GenerateToken() 和 IsValidToken(string) 方法。此示例中的算法与您从 Azure 生成的 Bearer 令牌不同,但您可以以某种方式对其进行自定义以匹配您的情况:

public static class TokenService
{
    public static int expireTime = 20;
    public static string GenerateToken()
    {
        byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
        var key = Guid.NewGuid().ToString();
        var salt = "somesalt";          
        byte[] securedKey = Encoding.ASCII.GetBytes(key + salt);
        string token = Convert.ToBase64String(time.Concat(securedKey).ToArray());
        return token;
    }

    public static bool IsValidToken(string token)
    {
        try
        {
            byte[] data = Convert.FromBase64String(token);
            //default expire time is 20 mins

            DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
            if (when < DateTime.UtcNow.AddMinutes(-expireTime))
            {
                return false;
            }

            return true;
        }
        catch (Exception ex)
        {
            new Exception("Unauthorized!");
        }

        return false;
    }
}

然后在 Startup.cs 文件中,设置 AuthenticationTokenProvider(在此示例中为 Microsoft.Owin.Security.Infrastructure),以便应用了解上述 TokenService 中的 GenerateToken() 方法

public class Startup
{      
    public void ConfigureOAuth(IAppBuilder app)
    {
        AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider();
        authTokenProvider.OnCreate = (context) =>
        {               
            context.SetToken(TokenService.GenerateToken());
        };

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,                              
            Provider = new SimpleAuthorizationServerProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(TokenService.expireTime),
            AccessTokenProvider = authTokenProvider,
            AuthorizationCodeProvider = authTokenProvider
        };

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

    }

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        ConfigureOAuth(app);            
    }
}

希望这会有所帮助!

【讨论】:

  • 我似乎无法在 SimpleAuthorizationServerProvider 上找到任何信息。有人可以帮忙吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-28
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
相关资源
最近更新 更多