OAuth的MVC实现(微软)

LoginController中:

第三方登陆

1
2
3
4
5
6
7
8
9
10
11
public ActionResult LogOn()
{
    string liveUrl =
        string.Format(
            "https://login.live.com/oauth20_authorize.srf?client_id={0}&scope=wl.Emails&response_type=code&redirect_uri={1}&locale={2}",
            this.ClientId,
            this.OAuthLogOnCallbackUrl,
            this.Locale);
 
    return this.Redirect(liveUrl);
}

登陆成功,获取授权 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public async Task<ActionResult> LogOnCallback()
{
    string code = this.Request.QueryString["code"];
 
    if (string.IsNullOrEmpty(code))
        return RedirectToAction("Index", "Login");
 
    string tokenUrl =
        string.Format(
            "https://login.live.com/oauth20_token.srf?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code&locale={4}",
            this.ClientId,
            this.OAuthLogOnCallbackUrl,
            this.ClientSecret,
            code,
            this.Locale);
 
    string liveId = string.Empty;
    try
    {
        liveId = await RequestLiveIdByToken(await RequestToken(tokenUrl));
    }
    catch (Exception e)
    {
        _logger.Fatal("无法获取LiveId Token", e);
        var result = new ViewModels.LoginResult
        {
            Success = false,
            ErrorMessage = "无法连接登录服务,请稍后再试。"
        };
        return View("Index", result);
    }
 
    if (!string.IsNullOrEmpty(liveId))
    {
        var userSvc = _userSvc;
        if (userSvc.CurrentUser == null)
        {
            UserInfo user = userSvc.GetUserByEmail(liveId);
 
            if (user != null && user.IsEnable)
            {
                return this.DoLogin(user);
            }
            else
            {
                var result = new ViewModels.LoginResult
                {
                    Success = false
                };
 
                if (user != null && !user.IsEnable)
                {
                    result.ErrorMessage = "用户被禁止登录!";
                }
                else
                {
                    result.ErrorMessage = "用户不存在!";
                }
 
                return View("Index", result);
            }
        }
 
        return this.DoLogin(userSvc.CurrentUser);
    }
 
    return this.RedirectToAction("Index", "Login");
}   

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[NonAction]
private async Task<string> RequestToken(string url)
{
    var request = WebRequest.Create(url);
 
    using (var response = await request.GetResponseAsync())
    {
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            var json = sr.ReadToEnd();
            return JsonConvert.DeserializeAnonymousType(json, new { access_token = "" }).access_token;
        }
    }
}
 
[NonAction]
private async Task<string> RequestLiveIdByToken(string token)
{
    if (string.IsNullOrEmpty(token))
        return string.Empty;
 
    var request = WebRequest.Create(string.Format("https://apis.live.net/v5.0/me?access_token={0}", token));
    using (var response = await request.GetResponseAsync())
    {
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            string json = sr.ReadToEnd();
            var userJson = JsonConvert.DeserializeAnonymousType(json, new { emails = new { account = "" } });
            return userJson.emails.account;
        }
    }
}

注销登陆 

1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult LogOff()
{
    this.PreLogout();
    string liveUrl =
        string.Format(
            "https://login.live.com/oauth20_logout.srf?client_id={0}&scope=wl.Emails&response_type=code&redirect_uri={1}&locale={2}",
            this.ClientId,
            this.OAuthLogOnCallbackUrl,
            this.Locale);
 
    return this.Redirect(liveUrl);
}

  

posted @   PanPan003  阅读(511)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示