集成OAuth认证

一、WebForms集成OAuth认证:

1、新建webform项目

2、添加Startup.cs文件

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Owin;
using System.IdentityModel.Tokens;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Linq;
using System.Security.Claims;
using IdentityModel.Client;
using Microsoft.IdentityModel.Protocols;

[assembly: OwinStartup(typeof(WebFormOwin.Startup))]

namespace WebFormOwin
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = true
            });

            //JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                SignInAsAuthenticationType = "Cookies",
                Authority = "https://auth-dev.veima.com",
                ClientId = "xiaomage",
                RedirectUri = "http://localhost:5000/",
                PostLogoutRedirectUri = "http://localhost:5000/",
                ResponseType = "id_token token",
                Scope = "openid profile",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var claims_to_exclude = new[]
                        {
                            "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
                        };

                        var claims_to_keep =
                            n.AuthenticationTicket.Identity.Claims
                            .Where(x => false == claims_to_exclude.Contains(x.Type)).ToList();
                        claims_to_keep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

                        if (n.ProtocolMessage.AccessToken != null)
                        {
                            claims_to_keep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));

                            var userInfoClient = new UserInfoClient(new Uri("https://auth-dev.veima.com/connect/userinfo"), n.ProtocolMessage.AccessToken);
                            var userInfoResponse = await userInfoClient.GetAsync();
                            var userInfoClaims = userInfoResponse.Claims
                                .Where(x => x.Item1 != "sub") // filter sub since we're already getting it from id_token
                                .Select(x => new Claim(x.Item1, x.Item2));
                            claims_to_keep.AddRange(userInfoClaims);
                        }

                        var ci = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            "name", "role");
                        ci.AddClaims(claims_to_keep);

                        n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(
                            ci, n.AuthenticationTicket.Properties
                        );
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var id_token = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
                            n.ProtocolMessage.IdTokenHint = id_token;
                        }

                        return Task.FromResult(0);
                    }
                }
            });
            app.UseStageMarker(PipelineStage.Authenticate);
        }
    }
}
View Code

3、添加引用类库dll

 

4、配置文件web.config中添加代码

assemblyBinding节点下:

<dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.20622.1351" newVersion="4.0.20622.1351" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocol.Extensions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.2.33" newVersion="1.0.2.33" />
      </dependentAssembly>

configuration节点下:

<location path="About">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>

 

二、MVC集成OAuth认证:

1、新建mvc项目

2、添加Startup.cs文件

using IdentityModel.Client;
using Microsoft.IdentityModel.Protocols;
using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

[assembly: OwinStartup(typeof(MvcOwin.Startup))]

namespace MvcOwin
{
    public class Startup
    {
        //public void Configuration(IAppBuilder app)
        //{
        //    //JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

        //    app.UseCookieAuthentication(new CookieAuthenticationOptions
        //    {
        //        AuthenticationType = "Cookies"
        //    });

        //    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        //    {
        //        Authority = "https://auth-dev.veima.com",
        //        ClientId = "xiaomage",
        //        RedirectUri = "http://localhost:5000/",
        //        PostLogoutRedirectUri = "http://localhost:5000/",
        //        ResponseType = "id_token token",
        //        Scope = "openid profile",
        //        UseTokenLifetime = false,
        //        SignInAsAuthenticationType = "Cookies",
        //    });
        //}
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = true
            });

            //JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                SignInAsAuthenticationType = "Cookies",
                Authority = "https://auth-dev.veima.com",
                ClientId = "xiaomage",
                RedirectUri = "http://localhost:5000/",//http://localhost:5000/
                PostLogoutRedirectUri = "http://localhost:5000/",
                ResponseType = "id_token token",
                Scope = "openid profile",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var claims_to_exclude = new[]
                        {
                            "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash"
                        };

                        var claims_to_keep =
                            n.AuthenticationTicket.Identity.Claims
                            .Where(x => false == claims_to_exclude.Contains(x.Type)).ToList();
                        claims_to_keep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

                        if (n.ProtocolMessage.AccessToken != null)
                        {
                            claims_to_keep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));

                            var userInfoClient = new UserInfoClient(new Uri("https://auth-dev.veima.com/connect/userinfo"), n.ProtocolMessage.AccessToken);
                            var userInfoResponse = await userInfoClient.GetAsync();
                            var userInfoClaims = userInfoResponse.Claims
                                .Where(x => x.Item1 != "sub") // filter sub since we're already getting it from id_token
                                .Select(x => new Claim(x.Item1, x.Item2));
                            claims_to_keep.AddRange(userInfoClaims);
                        }

                        var ci = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            "name", "role");
                        ci.AddClaims(claims_to_keep);

                        n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(
                            ci, n.AuthenticationTicket.Properties
                        );
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var id_token = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
                            n.ProtocolMessage.IdTokenHint = id_token;
                        }

                        return Task.FromResult(0);
                    }
                }
            });
            app.UseStageMarker(PipelineStage.Authenticate);
        }
    }
}
View Code

3、配置文件Web.config中assemblyBinding节点下添加代码:

<dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocol.Extensions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.2.33" newVersion="1.0.2.33" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.20622.1351" newVersion="4.0.20622.1351"/>
      </dependentAssembly>
View Code

4、控制器添加特性

[Authorize]
        public ActionResult Claims()
        {
            ViewBag.Message = "Claims";

            var cp = (ClaimsPrincipal)User;
            //ViewData["access_token"] = cp.FindFirst("access_token").Value;
            return View();
        }

5、退出登录

public ActionResult Signout()
        {
            // also possible to pass post logout redirect url via properties
            //var properties = new AuthenticationProperties
            //{
            //    RedirectUri = "http://localhost:2672/"
            //};

            Request.GetOwinContext().Authentication.SignOut();
            //return RedirectToAction("Index", "Home");
            return Redirect("/");
        }
View Code

6、页面显示登录信息

<dl>
    @foreach (var claim in System.Security.Claims.ClaimsPrincipal.Current.Claims)
    {
        <dt>
            @claim.Type
        </dt>
        <dd>
            @claim.Value
        </dd>
    }
</dl>


<ul>
    @foreach (var claim in ((System.Security.Claims.ClaimsPrincipal)User).Claims)
    {
        <li>@claim.Type + ", " + @claim.Value </li>
    }
</ul>
View Code

7、母版页显示注销按钮

@if (User.Identity.IsAuthenticated)
                    {
                        <li>@Html.ActionLink("Signout", "Signout", "Home")</li>
                    }
View Code

 

二、.Net Core Web项目集成OAuth认证:

1、新建core Web项目

2、Startup.cs文件添加代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CoreWebOwin
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = "Cookies";

                    options.Authority = "https://auth-dev.veima.com";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "xiaomage";
                    options.SaveTokens = true;
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
View Code

3、退出

public async Task Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            await HttpContext.SignOutAsync("oidc");
        }
View Code

 4、页面显示登录信息

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }
</dl>
View Code

 5、母版页显示注销按钮

@if (Context.User?.Identity?.IsAuthenticated ?? false)
                    {
                        <li><a asp-area="">@Context.User?.Claims.First(c => c.Type == "name").Value</a></li>

                        <li><a asp-action="Logout" asp-controller="Home">注销</a></li>
                    }
View Code

 

 

附:

官方实例:https://github.com/IdentityServer/IdentityServer3.Samples.git

转载于:https://www.cnblogs.com/SmilePastaLi/p/9753040.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成OAuth2可以实现用户身份验证和授权功能。OAuth2是一种用于授权的开放标准,允许用户授权第三方应用访问他们在其他服务提供商上的资源,而无需将用户名和密码提供给第三方应用。 要在Spring Boot应用程序中实现OAuth2,可以使用Spring Security和Spring Security OAuth2模块。下面是一个简单的步骤指南: 1. 添加依赖:在Maven或Gradle中添加Spring Security和Spring Security OAuth2的相关依赖。 2. 配置认证服务器:创建一个认证服务器配置类,继承自`AuthorizationServerConfigurerAdapter`,并重写`configure`方法来配置OAuth2的相关信息,如授权类型、客户端信息、访问令牌的有效期等。 3. 配置资源服务器:创建一个资源服务器配置类,继承自`ResourceServerConfigurerAdapter`,并重写`configure`方法来配置受保护的资源路径和访问规则。 4. 创建用户认证服务:创建一个实现了`UserDetailsService`接口的自定义用户认证服务类,用于从数据库或其他数据源中获取用户信息。 5. 配置Spring Security:创建一个继承自`WebSecurityConfigurerAdapter`的配置类,通过重写`configure`方法来配置Spring Security的行为,例如允许所有用户访问某些路径或强制用户进行身份验证。 6. 配置安全规则:在应用程序的配置文件(如application.properties)中,配置安全规则,如禁用CSRF保护、允许访问的路径等。 7. 创建登录页面:根据需要创建一个登录页面,用于用户进行身份验证。 以上是一个基本的步骤指南,具体实现可能会根据你的应用程序需求而有所不同。你可以参考Spring官方文档和示例代码来更详细地了解和实现Spring Boot集成OAuth2的过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值