Claims ASP.NET MVC with External Authentication

Background

Our web applications use external authentication, in a sense that user names / passwords are not verified locally, but are checked "outside" the web application on a central website with one login sign. Authentication (and user authentication) is made available through the local server variables ( HTTP_EMPLOYEEIDetc.). However, it is not entirely external, like Google, Facebook, or other OAuth-based authentication. Therefore, I just wanted to make this distinction, so it does not come across the terms “External Logins” in ASP.NET Identity / Owin.

Problem

I am trying to figure out a clean way to use authenticated user data (from server variables) and pass it to ASP.NET authentication. However, the user profile and role data must be searched in the web service before the user can log into the application.

I want to use the Owin and Claims identifier, but I'm not sure if I should also use the ASP.NET ID , or just make a cleaner implementation with claims, I like the idea of ​​not reinventing the wheel, but I also don't want to force the square snapping into a round hole (as they say), if the method of user identification and search from a web service does not fit the typical use of an ASP.NET identifier.

For example, if I use a more purist approach, I could do something like:

// Get the current user id
var userId = HttpContext.Current.Request.ServerVariables["HTTP_EMPLOYEEID"];

// Get profile and role data from a web service
MyUser user = MyUserService.GetUserById(userId);

// Create claims
var claims = new Claim[]
{
    new Claim(ClaimTypes.Name, user.Id),
    new Claim(ClaimTypes.Email, user.Email),
    new Claim(ClaimTypes.Role, user.Role), // there can be more roles, but you get the idea
    // etc.
};

// Establish identity and login
var identity = new ClaimsIdentity(claims, "CookieAuthentication");
HttpContext.Current.GetOwinContext().Authentication.SignIn(identity);

But I also know that I could use ASP.NET Identity (just without the Entity Framework stuff) and just implement IUser, IUserStore, IRoleStore (and all that is minimally necessary), and use Microsoft’s existing installed infrastructure to handle this. The argument should be that this is more in line with current standards and could potentially be simplified more easily for other types of authentication (if, say, a local username / password or Google / Facebook becomes the other allowed authentication options in the end, in addition to Current ServerVariables setting).

, ? , , ASP.NET, , , "" , ?

p.s. ASP.NET 4.6.1, ​​ASP.NET.

+4
1

. ASP.Net, .

OWIN Claim Authentication, cookie ; , .

public class OwinAuthenticationService 
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Sid, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        foreach (Role role in user.Roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, role.Name));
        }

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}

Startup.cs

. Angular MVC Web API, 404 REST 404 Page.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnApplyRedirect = ctx =>
                {
                    if (!IsApiRequest(ctx.Request))
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                }
            }
        });
    }

    private static bool IsApiRequest(IOwinRequest request)
    {
        string apiPath = VirtualPathUtility.ToAbsolute("~/api/");
        return request.Uri.LocalPath.ToLower().StartsWith(apiPath);
    }
}
+1

Source: https://habr.com/ru/post/1648565/


All Articles