OpenIddict Token

namespace Tokens
{
    public class PostTokenDto
    {
        public string? Access_token { get; set; }
        public string? Token_type { get; set; }
        public int? Expires_in { get; set; }
    }
}
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace Tokens
{
    public interface ITokenAppService : IApplicationService
    {
        Task<PostTokenDto?> Post();
    }
}
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Identity;

namespace Tokens
{
    public class TokenAppService(
        IdentityUserManager userManager,
        IHttpClientFactory httpClientFactory,
        SignInManager<IdentityUser> signInManager,
        IHttpContextAccessor httpContextAccessor) : IspWebAppService, ITokenAppService
    {
        public async Task<PostTokenDto?> Post()
        {
            var AuthServer =
                httpContextAccessor.HttpContext.Request.IsHttps ? "https://" +
                httpContextAccessor.HttpContext.Request.Host.Value : "http://" +
                httpContextAccessor.HttpContext.Request.Host.Value;

            var client = httpClientFactory.CreateClient(AuthServer);

            client.BaseAddress = new Uri(AuthServer);

            var userName = "admin";
            var password = "1q2w3E*";

            var dic = new Dictionary<string, object>
            {
                {"client_id","IspWeb_App"},
                { "client_secret","1q2w3e*"},
                { "grant_type","password"},
                { "scope","IspWeb"},
                { "username",userName},
                { "password",password },
                { "SaveTokens",true }
            };

            var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
            HttpContent httpContent = new StringContent(dicStr!);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            var oauthRep = await client.PostAsync("connect/token", httpContent);

            var oauthStr = await oauthRep.Content.ReadAsStringAsync();

            var oauthResult = default(PostTokenDto);

            if (oauthRep.IsSuccessStatusCode)
            {
                if (!string.IsNullOrEmpty(oauthStr))
                {
                    oauthResult = JsonConvert.DeserializeObject<PostTokenDto>(oauthStr);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(oauthStr) || oauthStr.Contains("error"))
                    throw new UserFriendlyException(oauthRep.ReasonPhrase!);
            }

            var result = await signInManager.PasswordSignInAsync(userName, password, true, true);
            if (!result.Succeeded)
                throw new UserFriendlyException("账号或者密码不正确!");
            else if (result.IsLockedOut)
                throw new UserFriendlyException("登录失败,该账户已被锁定!");

            var user = await userManager.FindByNameAsync(CurrentUser.UserName!);

            var roles = await userManager.GetRolesAsync(user!);
            if (roles == null || roles.Count == 0)
                throw new UserFriendlyException("当前用户未分配角色");

            return oauthResult;
        }
    }
}

 

posted @ 2024-10-24 13:41  邪不压正!  阅读(14)  评论(0编辑  收藏  举报