pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

帶有 OpenIdAuthentication 的 ASP.NET:如果未授權,則重

ASP.NET with OpenIdAuthentication: redirect to url if not authorized(帶有 OpenIdAuthentication 的 ASP.NET:如果未授權,則重定向到 url)
本文介紹了帶有 OpenIdAuthentication 的 ASP.NET:如果未授權,則重定向到 url的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在嘗試編寫一個使用混合身份驗證方案的 ASP.NET 應用程序.用戶可以將其用戶名和密碼哈希存儲在 UserStore 中,也可以通過 Azure Active Directory 進行身份驗證.

I am attempting to write an ASP.NET application that uses a hybrid authentication scheme. A user can either have his username and password hash stored in the UserStore, or he can authenticate via Azure Active Directory.

我已經創建了如圖所示的登錄表單.它具有標準的 UserNamePassword 輸入,還具有通過 Active Directory 登錄"按鈕.

I have created the login form pictured. It has the standard UserName and Password inputs, but also has a "Login via Active Directory" button.

這很好用.

現在解決問題:應用程序的主頁具有 [Authorize] 屬性.

Now for the problem: The application's home page has the [Authorize] attribute.

public class DefaultController : Controller
{
    [Authorize]
    public ViewResult Index()
    { 
    // Implementation
    }
}

如果用戶沒有登錄,我希望它重定向到頁面Account/Login,讓用戶選擇認證方式.

If the user is not logged in, I want it to redirect to the page Account/Login, allowing the user to choose the authentication method.

IAppBuilder.UseOpenIdConnectAuthentication 添加到管道設置后,它不再重定向到該頁面.相反,它直接進入 Microsoft 登錄頁面.

Once I added IAppBuilder.UseOpenIdConnectAuthentication to the pipeline setup, it no longer redirects to that page. Instead, it goes straight to the Microsoft Login page.

我如何配置它以使 OpenID 身份驗證成為系統的一部分,但允許我指定在用戶未通過身份驗證時如何執行重定向?

How do I configure it so that OpenID authentication is part of the system, but allow me to specify how to perform redirections when the user is not authenticated?

這是我設置管道的代碼:

Here's the code where I set up the pipeline:

appBuilder.SetDefaultSignInAsAuthticationType(CookieAuthenticationDefaults.AuthenticationType_;
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationType.ApplicationCookie,
     LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
     Provider = new Security.CookieAuthenticationProvider()
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);
// Now the OpenId authentication
var notificationHandlers = new OpenIdConnectAuthenticationNotificationHandlers 
{
   AuthorizationCodeReceived = async(context) => {
       var jwtSecurityToken = context.JwtSecurityToken;
       // I've written a static method to convert the claims
       // to a user
       var user = await GetOrCreateUser(context.OwinContext, jwtSecurityToken.Claims);
       var signInManager = context.OwinContext.Get<SignInManager>();
       await signInManager.SignInAsync(user, true, false);
   }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);

當您單擊Active Directory 登錄"時,它會發布到Account/SignInWithOpenId"

When you click "Active Directory Signin", it posts to "Account/SignInWithOpenId"

public ActionResult SignInWithOpenId()
{
    // Send an OpenID Connect sign-in request.
    if (!Request.IsAuthenticated)
    {
        var authenticationProperties = new AuthenticationProperties
        {
            RedirectUri = "/"
        };
        HttpContext.GetOwinContext().Authentication.Challenge
        (
            authenticationProperties,
            OpenIdConnectAuthenticationDefaults.AuthenticationType
        );
        return new EmptyResult();
    }
    else
    {
        return RedirectToAction("Index", "Default");
    }
}

推薦答案

IAppBuilder.UseOpenIdConnectAuthentication(...) 的調用將 Owin 中間件組件放入管道中.當 ASP.NET MVC 返回 401(未授權)的 HttpResponse 時,Owin 中間件組件會檢測到這一點并將其更改為 Http Redirect(代碼 302),并且重定向路徑是 Open Id 提供程序.

The call to IAppBuilder.UseOpenIdConnectAuthentication(...) puts an Owin middleware component in the pipeline. When ASP.NET MVC returns an HttpResponse of 401 (Unauthorized), the Owin Middleware component detects this and changes it to an Http Redirect (code 302), and the redirection path is to the Open Id provider.

但是有一種方法可以解決這個問題:在中間件組件執行重定向之前,它會調用回調 RedirectToIdentityProvider.從這里,您可以覆蓋此重定向.

But there's a way to get around this: before the middleware component performs the redirect, it invokes the callback RedirectToIdentityProvider. From here, you can override this redirection.

這是我的代碼,它會覆蓋重定向,除非它來自請求路徑 Account/SignInWithOpenId.

Here is my code that overrides the redirection unless it is from the request path Account/SignInWithOpenId.

var notificationHandlers = new OpenIdConnectAuthenticationNotifications
{
    AuthorizationCodeReceived = async(context) => {
       // Sign in the user here
    },
    RedirectToIdentityProvider = (context) => {
        if(context.OwinContext.Request.Path.Value != "/Account/SignInWithOpenId")
        {
             context.OwinContext.Response.Redirect("/Account/Login");
             context.HandleResponse();
        }
        return Task.FromResult(0);
    }
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
     ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
     Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
     PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
     Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);

這篇關于帶有 OpenIdAuthentication 的 ASP.NET:如果未授權,則重定向到 url的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
ASP Core Azure Active Directory Login use roles(ASP Core Azure Active Directory 登錄使用角色)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發技
.Net Core 2.0 - Get AAD access token to use with Microsoft Graph(.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用)
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
主站蜘蛛池模板: 环保袋,无纺布袋,无纺布打孔袋,保温袋,环保袋定制,环保袋厂家,环雅包装-十七年环保袋定制厂家 | 水冷式工业冷水机组_风冷式工业冷水机_水冷螺杆冷冻机组-深圳市普威机械设备有限公司 | 合肥风管加工厂-安徽螺旋/不锈钢风管-通风管道加工厂家-安徽风之范 | 定时排水阀/排气阀-仪表三通旋塞阀-直角式脉冲电磁阀-永嘉良科阀门有限公司 | 针焰试验仪,灼热丝试验仪,漏电起痕试验仪,水平垂直燃烧试验仪 - 苏州亚诺天下仪器有限公司 | 广西教师资格网-广西教师资格证考试网 | 不锈钢散热器,冷却翅片管散热器厂家-无锡市烨晟化工装备科技有限公司 | NMRV减速机|铝合金减速机|蜗轮蜗杆减速机|NMRV减速机厂家-东莞市台机减速机有限公司 | 行星齿轮减速机,减速机厂家,山东减速机-淄博兴江机械制造 | 武汉刮刮奖_刮刮卡印刷厂_为企业提供门票印刷_武汉合格证印刷_现金劵代金券印刷制作 - 武汉泽雅印刷有限公司 | 振动台-振动试验台-振动冲击台-广东剑乔试验设备有限公司 | 砍排机-锯骨机-冻肉切丁机-熟肉切片机-预制菜生产线一站式服务厂商 - 广州市祥九瑞盈机械设备有限公司 | 工作心得_读书心得_学习心得_找心得体会范文就上学道文库 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | 除尘器布袋骨架,除尘器滤袋,除尘器骨架,电磁脉冲阀膜片,卸灰阀,螺旋输送机-泊头市天润环保机械设备有限公司 | 查分易-成绩发送平台官网 | (中山|佛山|江门)环氧地坪漆,停车场地板漆,车库地板漆,聚氨酯地板漆-中山永旺地坪漆厂家 | 广东泵阀展|阀门展-广东国际泵管阀展览会| 陶瓷砂磨机,盘式砂磨机,棒销式砂磨机-无锡市少宏粉体科技有限公司 | 工业淬火油烟净化器,北京油烟净化器厂家,热处理油烟净化器-北京众鑫百科 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 临时厕所租赁_玻璃钢厕所租赁_蹲式|坐式厕所出租-北京慧海通 | 石栏杆_青石栏杆_汉白玉栏杆_花岗岩栏杆 - 【石雕之乡】点石石雕石材厂 | 海水晶,海水素,海水晶价格-潍坊滨海经济开发区强隆海水晶厂 | 济南ISO9000认证咨询代理公司,ISO9001认证,CMA实验室认证,ISO/TS16949认证,服务体系认证,资产管理体系认证,SC食品生产许可证- 济南创远企业管理咨询有限公司 郑州电线电缆厂家-防火|低压|低烟无卤电缆-河南明星电缆 | 电磁流量计_智能防腐防爆管道式计量表-金湖凯铭仪表有限公司 | 山东信蓝建设有限公司官网| 立式硫化罐-劳保用品硫化罐-厂家直销-山东鑫泰鑫硫化罐厂家 | 优考试_免费在线考试系统_培训考试系统_题库系统_组卷答题系统_匡优考试 | 激光内雕_led玻璃_发光玻璃_内雕玻璃_导光玻璃-石家庄明晨三维科技有限公司 激光内雕-内雕玻璃-发光玻璃 | 曙光腾达官网-天津脚手架租赁-木板架出租-移动门式脚手架租赁「免费搭设」 | 聚氨酯催化剂K15,延迟催化剂SA-1,叔胺延迟催化剂,DBU,二甲基哌嗪,催化剂TMR-2,-聚氨酯催化剂生产厂家 | 超声波分散机-均质机-萃取仪-超声波涂料分散设备-杭州精浩 | 砂尘试验箱_淋雨试验房_冰水冲击试验箱_IPX9K淋雨试验箱_广州岳信试验设备有限公司 | 电动百叶窗,开窗器,电动遮阳百叶,电动开窗机生产厂家-徐州鑫友工控科技发展有限公司 | 北京自然绿环境科技发展有限公司专业生产【洗车机_加油站洗车机-全自动洗车机】 | TPE_TPE热塑性弹性体_TPE原料价格_TPE材料厂家-惠州市中塑王塑胶制品公司- 中塑王塑胶制品有限公司 | 塑料撕碎机_编织袋撕碎机_废纸撕碎机_生活垃圾撕碎机_废铁破碎机_河南鑫世昌机械制造有限公司 | 螺纹三通快插接头-弯通快插接头-宁波舜驰气动科技有限公司 | ERP企业管理系统永久免费版_在线ERP系统_OA办公_云版软件官网 | 恒湿机_除湿加湿一体机_恒湿净化消毒一体机厂家-杭州英腾电器有限公司 |