使用AD和OWIN保护端点

时间:2018-06-12 23:16:22

标签: c# asp.net asp.net-web-api

我目前正在尝试使用我们的域AD对网络应用的用户进行身份验证,到目前为止我已成功登录。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var authService = new ADAuthenticationService(AuthenticationManager);

    var authenticationResult = authService.SignIn(model.Email, model.Password);

    if (authenticationResult.IsSuccess)
    {
        // To home/index since no returnUrl is actually being captured for now
        return RedirectToLocal(returnUrl);
    }

    ModelState.AddModelError("", authenticationResult.ErrorMessage);
    return View(model);
}

我的身份验证服务会创建一个声明标识并对用户进行签名。接下来,我想保护我的web api端点,以便只允许登录的客户端向其发送请求。举个例子,我有以下几点:

[HttpPost]
public ActionResult Authorize()
{
    var claims = new ClaimsPrincipal(User).Claims.ToArray();
    var identity = new ClaimsIdentity(claims, "Bearer");
    AuthenticationManager.SignIn(identity);
    return new EmptyResult();
}

但是,当我真正尝试去端点时,它告诉我我是未经授权的。在请求标头中,我有“授权:承载令牌”。

编辑: 在Startup.Auth.cs中,我已将auth配置为

static Startup()
{
    PublicClientId = "web";

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        AuthorizeEndpointPath = new PathString("/Account/Authorize"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };
}
public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
         AuthenticationType = ADAuthentication.ApplicationCookie,
         LoginPath = new PathString("/Account/Login"),
         Provider = new CookieAuthenticationProvider
         {
              OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(validateInterval: TimeSpan.FromMinutes(20),
              regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
         },
         CookieName = "MyAppAuthenticationType",
         CookieHttpOnly = true,
         ExpireTimeSpan = TimeSpan.FromHours(1),
    });
    app.UseOAuthBearerTokens(OAuthOptions);
}

编辑2: ADAuthenticationService.cs

public ADAuthenticationService(IAuthenticationManager authenticationManager)
{
    this.authenticationManager = authenticationManager;
}


public AuthenticationResult SignIn(String username, String password)
{
    PrincipalContext principalContext = new PrincipalContext(authenticationType);
    bool isAuthenticated = false;
    UserPrincipal userPrincipal = null;
    try
    {
        userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
        if (userPrincipal != null)
        {
            isAuthenticated = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate);
        }
    }
    catch (Exception exception)
    {
        System.Diagnostics.Debug.WriteLine(exception);
        return new AuthenticationResult("Username or Password is not correct");
    }

    /* some other invalid login results here */

    var identity = CreateIdentity(userPrincipal);

    authenticationManager.SignOut(ADAuthentication.ApplicationCookie);
    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);


    return new AuthenticationResult();
}


private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
{
    var identity = new ClaimsIdentity(ADAuthentication.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
        identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
        identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.SamAccountName));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
    if (!String.IsNullOrEmpty(userPrincipal.EmailAddress))
    {
        identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));
    }

    var groups = userPrincipal.GetAuthorizationGroups();
    foreach (var @group in groups)
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, @group.Name));
    }

    return identity;
}

0 个答案:

没有答案