.NET 6 OAuth2.0 IdentityServer4 4.X PasswordToken(创建Token) RefreshToken(刷新Token) RevokeToken(撤销Token

.NET Core OAuth IdentityServer4 AllowAnonymous Policy 白名单 .NET 5 IdentityServer4 4.X版本
jwt.io
最小 API 概述
使用 ASP.NET Core 创建最小 Web API
IdentityServer4 1.0.0 documentation 官网 
Token Endpoint 
    Requesting a token 
    Requesting a token using the client_credentials  Grant Type 
    Requesting a token using the password  Grant Type 
    Requesting a token using the authorization_code Grant Type 
    Requesting a token using the refresh_token Grant Type 
    Requesting a Device Token 
Token Introspection Endpoint 
Token Revocation Endpoint 
UserInfo Endpoint 

1、Program.cs

using AuthService;
using AuthService.CoreLibrary;
using AuthService.Filters;
using System.Data;
using System.Data.SqlClient;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

string[] address = builder.Configuration["AppSettings:CorsAddress"].Split(',');
string[] port = builder.Configuration["AppSettings:CorsPort"].Split(',');

builder.Services.Configure<RedisOptions>(builder.Configuration.GetSection("RedisOptions"));
RedisOptions redisOptions = new RedisOptions();
builder.Configuration.Bind("RedisOptions", redisOptions);
string host = redisOptions.Host;
string port = redisOptions.Port;

//加载自定义配置文件
var config = builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("CustomConfig.json", optional: true, reloadOnChange: true);
});
//读取 CustomConfig.json 文件 SmtpServer 配置项
var smtp = builder.Configuration["SmtpServer"];

#region 数据库 EF Core
builder.Services.AddDbContext<AssetDbContext>(options =>
  options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
#endregion

#region 数据库 Dapper
string dbType = builder.Configuration["DbSql:DbType"];
switch (dbType)
{
    case "SqlServer":
        //builder.Services.AddSingleton(builder.Configuration.GetConnectionString("DefaultConnection"));
        builder.Services.AddSingleton(builder.Configuration["DbSql:SqlServerConnection"]);
        break;
    default:
        break;
}

builder.Services.AddSingleton<IDbConnection, SqlConnection>();
builder.Services.AddSingleton<IUserRepository, UserRepository>();
builder.Services.AddSingleton<IUserLogRepository, UserLogRepository>();
builder.Services.AddSingleton<ILogUserLoginRepository, LogUserLoginRepository>();
#endregion

#region
builder.Services.AddIdentityServer(options => { })
    .AddDeveloperSigningCredential()
    .AddInMemoryClients(AuthService.Security.Clients.GetClients())
    .AddInMemoryIdentityResources(AuthService.Security.IdentityConfig.GetIdentityResources())
    .AddInMemoryApiResources(AuthService.Security.IdentityConfig.GetResources())
#region ids4 4.X 新特性 
    .AddInMemoryApiScopes(AuthService.Security.IdentityConfig.GetScopes())
    //.AddInMemoryApiScopes(Security.IdentityConfig.ApiScopes)
#endregion
    .AddProfileService<AuthService.Security.ProfileService>()
    .AddResourceOwnerValidator<AuthService.Security.ResourceOwnerPasswordValidator>();
#endregion

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

#region 跨域访问
string AllowSpecificOrigins = "AllowSpecificOrigins";
var urls = StringPlus.GetCors(address, port);
builder.Services.AddCors(options =>
{
    options.AddPolicy(AllowSpecificOrigins, builder =>
    {
        builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
    });
});
#endregion

builder.Services.AddControllers(options =>
{
    options.Filters.Add(typeof(CustomExceptionFilter));
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/", () => "Hello World!");

app.MapGet("/api/users/{text}", (string text) => $"{text}");

app.MapGet("/GetData", (IUserRepository userRep) => 
{
    return userRep.GetList();
})
.WithName("GetData");

app.MapGet("/api/users/{userId}/books/{bookId}", (int userId, int bookId) => new
{
    code = 200,
    data = new
    {
        user = userId,
        book = bookId
    },
    message = ""
});

app.MapGet("/api/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    (
        DateTime.Now.AddDays(index),
        Random.Shared.Next(-20, 55),
        summaries[Random.Shared.Next(summaries.Length)]
    )).ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.UseHttpsRedirection();

app.UseIdentityServer();
app.UseRouting();

app.UseCors(AllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

2、StringPlus.cs

using System.Text;

namespace AuthService.CoreLibrary
{
    public class StringPlus
    {
        public static string[] StringToStrArray(string str)
        {
            string[] strArray = null;
            if (!string.IsNullOrEmpty(str))
            {
                strArray = str.Split(',');
            }
            return strArray;
        }

        public static string[] GetCors(string[] address, string[] port)
        {
            string[] array = null;
            if (address != null && port != null)
            {
                StringBuilder cors = new StringBuilder();
                for (int i = 0; i <= address.Length - 1; i++)
                {
                    for (int j = 0; j <= port.Length - 1; j++)
                        cors.Append($"{address[i]}:{port[j]},");
                }
                string url = cors.ToString();
                if (!string.IsNullOrEmpty(url))
                    array = StringToStrArray(url.Substring(0, url.LastIndexOf(",")));
            }
            return array;
        }
    }
}

3、RedisOptions.cs

public class RedisOptions
{
    public string Host { get; set; }
    public string Port { get; set; }
}

4、appsettings.json【注意:TrustServerCertificate=true】

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "data source=192.168.159.130;initial catalog=dbTest;user id=sa;password=000000;TrustServerCertificate=true;"
  }
}

5、.NET 5 IdentityServer4 4.X版本配置【\AuthService\Security\IdentityConfig.cs】

using AuthService.CoreLibrary;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
namespace AuthService.Security
{
  public class IdentityConfig
  {
    public static IEnumerable<ApiResource> GetResources()
    {
      return new List<ApiResource>
      {
        new ApiResource(ConfigManager.Configuration["IdentityAuthentication:Scope"],ConfigManager.Configuration["IdentityAuthentication:ClientName"])
        {
          #region ids4 4.X 新特性
          Scopes = { "Asset",ConfigManager.Configuration["IdentityAuthentication:Scope"]},
          #endregion
          ApiSecrets = { new Secret(ConfigManager.Configuration["IdentityAuthentication:Secret"].Sha256()) }
        }
      };
    }
 
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
      return new IdentityResource[]
      {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
      };
    }
 
    /// <summary>
    /// ids4 4.X 新特性
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<ApiScope> GetScopes()
    {
      return new ApiScope[]
      {
        new ApiScope("Asset"),
        new ApiScope(ConfigManager.Configuration["IdentityAuthentication:Scope"]),
      };
    }
 
    /// <summary>
    /// ids4 4.X 新特性
    /// </summary>
    public static IEnumerable<ApiScope> ApiScopes =>
      new ApiScope[]
      {
        new ApiScope("Asset"),
        new ApiScope(ConfigManager.Configuration["IdentityAuthentication:Scope"]),
      };
  }
}

6、Controller
RequestPasswordTokenAsync:创建Token
RequestRefreshTokenAsync:刷新Token
RevokeTokenAsync:撤销Token

using AutoMapper;
using Azure.Core;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using static IdentityModel.OidcConstants;

namespace WebAPI.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/passport/[action]")]
    public class PassportController : ControllerBase
    {
        private readonly string url = string.Empty;

        private readonly IUserRepository _userRepo;
        private readonly IConfiguration _configuration;
        private readonly IHttpClientHelper _client;
        private readonly MsgResult _msgResult;
        private readonly IMapper _mapper;
        private readonly ILogger _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userRepo"></param>
        /// <param name="configuration"></param>
        /// <param name="client"></param>
        /// <param name="msgResult"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public PassportController(IUserRepository userRepo, IConfiguration configuration, IHttpClientHelper client, MsgResult msgResult, IMapper mapper, ILogger<PassportController> logger)
        {
            _userRepo = userRepo;
            _configuration = configuration;
            _client = client;
            _msgResult = msgResult;
            _mapper = mapper;
            _logger = logger;
            url = _configuration["IdentityAuthentication:Authority"]!;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MsgResult> Login([FromBody] LoginRequest request)
        {
            #region token
            //Dictionary<string, string> parm = new Dictionary<string, string>();
            //parm.Add("grant_type", "password");
            //parm.Add("client_Id", _configuration["IdentityAuthentication:ApiName"]!);
            //parm.Add("client_secret", _configuration["IdentityAuthentication:ApiSecret"]!);
            //parm.Add("username", request.user_name);
            //parm.Add("password", request.password);
            //parm.Add("user_type", "Admin");
            //parm.Add("scope", $"{_configuration["IdentityAuthentication:ApiName"]} openid offline_access");

            //string tokenJson = await _client.PostAsync($"{url}/connect/token", StringPlus.DictionaryToString(parm), "application/x-www-form-urlencoded");
            //TokenDto token = JsonConvert.DeserializeObject<TokenDto>(tokenJson);
            //if (token != null)
            //{
            //    _msgResult.code = token.code;
            //    _msgResult.data = token;
            //    _msgResult.message = token.message;
            //}
            #endregion

            #region
            IdentityModel.Client.TokenResponse tokenRes = await new HttpClient().RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = $"{url}/connect/token",
                GrantType = "password",
                ClientId = _configuration["IdentityAuthentication:ApiName"]!,
                ClientSecret = _configuration["IdentityAuthentication:ApiSecret"]!,
                UserName = request.user_name,
                Password = request.password,
                Scope = $"{_configuration["IdentityAuthentication:ApiName"]} openid offline_access",
                Parameters = new Dictionary<string, string>()
                {
                    { "user_type","Admin"}
                }
            });

            if (tokenRes != null)
            {
                _msgResult.code = 1;
                _msgResult.data = tokenRes.Json;
                _msgResult.message = "";
            }
            #endregion

            return _msgResult;
        }

        /// <summary>
        /// 刷新token
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<MsgResult> RefreshToken([FromBody] QualityControl.Models.RefreshTokenRequest request)
        {
            #region
            //Dictionary<string, string> parm = new Dictionary<string, string>();
            //parm.Add("grant_type", "refresh_token");
            //parm.Add("client_Id", _configuration["IdentityAuthentication:ApiName"]!);
            //parm.Add("client_secret", _configuration["IdentityAuthentication:ApiSecret"]!);
            //parm.Add("refresh_token", request.refresh_token);

            //string tokenJson = await _client.PostAsync($"{url}/connect/token", StringPlus.DictionaryToString(parm), "application/x-www-form-urlencoded");
            //TokenDto token = JsonConvert.DeserializeObject<TokenDto>(tokenJson);

            //if (token != null)
            //{
            //    _msgResult.code = token.code;
            //    _msgResult.data = token;
            //    _msgResult.message = token.message;
            //}
            #endregion

            #region
            IdentityModel.Client.TokenResponse tokenRes = await new HttpClient().RequestRefreshTokenAsync(new IdentityModel.Client.RefreshTokenRequest
            {
                Address = $"{url}/connect/token",
                RefreshToken = request.refresh_token,
                GrantType = "refresh_token",
                ClientId = _configuration["IdentityAuthentication:ApiName"]!,
                ClientSecret = _configuration["IdentityAuthentication:ApiSecret"]!,
            });

            if (tokenRes != null)
            {
                _msgResult.code = 1;
                _msgResult.data = tokenRes.Json;
                _msgResult.message = "";
            }
            #endregion

            return _msgResult;
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost()]
        public async Task<MsgResult> Logout()
        {
            string token = HttpContext.Request.Headers["Authorization"].ToString().Replace("bearer ", "").Replace("Bearer ", "");
            HttpClient client = new HttpClient();
            await client.RevokeTokenAsync(new TokenRevocationRequest
            {
                Address = $"{url}/connect/revocation",
                ClientId = _configuration["IdentityAuthentication:ApiName"]!,
                ClientSecret = _configuration["IdentityAuthentication:ApiSecret"]!,
                Token = token,
            });

            _msgResult.code = 1;
            _msgResult.message = "退出成功";

            return _msgResult;
        }
    }
}

*
*
*

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
嗨!关于Spring Boot整合Spring Security和OAuth2.0实现token认证,你可以按照以下步骤进行操作: 1. 添加依赖:在你的Spring Boot项目的pom.xml文件中,添加Spring Security和OAuth2.0相关的依赖。 ```xml <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> </dependencies> ``` 2. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法来配置Spring Security的行为。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID"); } } ``` 在上述配置中,我们允许访问一些特定的URL(如/oauth2/**,/login/**和/logout/**),并保护所有其他URL。我们还设置了自定义的登录页面和注销成功后的跳转页面。 3. 配置OAuth2.0:创建一个继承自AuthorizationServerConfigurerAdapter的配置类,并重写configure方法来配置OAuth2.0的行为。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("client_id") .secret("client_secret") .authorizedGrantTypes("authorization_code", "password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600) .refreshTokenValiditySeconds(86400); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager); } } ``` 在上述配置中,我们使用内存存储客户端信息(client_id和client_secret),并配置了授权类型(如authorization_code、password和refresh_token)。我们还设置了访问令牌和刷新令牌的有效期。 4. 创建登录页面:创建一个HTML登录页面,用于用户进行身份验证并获取访问令牌。 ```html <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" /> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" /> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html> ``` 5. 处理登录请求:创建一个控制器来处理登录请求,并在登录成功后重定向到受保护的资源。 ```java @Controller public class LoginController { @GetMapping("/login") public String showLoginForm() { return "login"; } @PostMapping("/login") public String loginSuccess() { return "redirect:/protected-resource"; } } ``` 在上述控制器中,我们使用@GetMapping注解来处理GET请求,@PostMapping注解来处理POST请求。登录成功后,我们将用户重定向到受保护的资源。 这样,你就完成了Spring Boot整合Spring Security和OAuth2.0实现token认证的配置。你可以根据自己的需求进行进一步的定制和扩展。希望对你有所帮助!如果你有任何疑问,请随时问我。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值