将未经授权的请求重定向到Azure AD进行登录 [英] Redirect unauthorized requests to Azure AD for login

查看:73
本文介绍了将未经授权的请求重定向到Azure AD进行登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在Azure中运行的WebAPI实例,该实例由Azure AD保护.移动应用程序使用承载令牌连接到此API,效果很好.但是,当我尝试从浏览器调用API时,由于未登录,它会返回401.这是正确的,因为没有显示登录屏幕.

I've got a WebAPI instance running in Azure that is secured with Azure AD. A mobile app connects to this API using bearer tokens, works great. When I try calling the API from the browser, though, it returns a 401 because I'm not logged in. That's true because I'm not presented with a login screen.

我的API没有任何UI,所以我想要做的就是将用户转发到Azure AD登录并返回到身份验证后调用的API终结点.

My API doesn't have any UI so what I'd want it to do is to forward the user to Azure AD login and return to the API endpoint they were calling after authentication.

如果我转到Azure门户,则存在一个设置,内容为在未授权请求时应采取的措施".如果将其设置为使用Azure Active Directory登录",它将按照我希望的方式运行.但是...我有一些端点需要匿名访问,并且此设置捕获所有请求,而不关心任何[AllowAnonymous]属性.

If I go to the Azure portal, there's a setting that says "Action to take when the request is not authorized". If I set that one to "Log in with Azure Active Directory", it behaves the way I want it to. But... I have some endpoints which need to be accessed anonymously, and this setting catches all requests, not caring about any [AllowAnonymous] attributes.

因此,对未授权的标记为授权"的终结点的任何请求都应转发到Azure AD登录,应允许所有其他请求.

So any request to an endpoint labeled Authorize that is not authorized yet should be forwarded to Azure AD login, all others should be allowed.

推荐答案

DelegatingHandler添加到您的Web api项目并在WebApiConfig.cs中注册它:

Add a DelegatingHandler to your web api project and register it in WebApiConfig.cs:

config.MessageHandlers.Add(new UnAuthorizedDelegatehandler());

public class UnAuthorizedDelegatehandler: DelegatingHandler

您可以在其中检查401状态代码,并执行重定向到任何操作,还可以将重定向URL用作querystring参数.

There you can check for 401 status codes and do the redirect to whatever and also apply a redirect url as querystring parameter.

HttpResponseMessage rm = await base.SendAsync(request, cancellationToken);
if (rm.StatusCode == HttpStatusCode.Unauthorized)
{
    // configure the redirect here
    return rm;                        
}

这篇关于将未经授权的请求重定向到Azure AD进行登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆