identityservice4使用案例

 

一 使用缘由                                                     

                  

    最近写微服务的blog,研读了o’reilly出的 《building Microservices With Asp.net Core》,其中使用的微服务分布式权限组件是microsoft.aspnetcore.authentication.jwtbearer,那最近identityserver4这么流行,就决定替换掉它。

 

二 开始                                                                                 

 

1 认证流程:

                                                                       image

2 开发

    

    认证服务器:

            (1)  首先一个空的asp.net core 项目,在nuget包中安装identityserver4 包

            (2)  项目组织,会增加Config.cs的文件。

                                                                                     image

 

 

相关代码

using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Walt.Freamwork.Sec
{
    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
                {
                    new ApiResource("api1", "My API")
                };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
                    {
                        new Client
                        {
                            ClientId = "client",

                            // no interactive user, use the clientid/secret for authentication
                            AllowedGrantTypes = GrantTypes.ClientCredentials,

                            // secret for authentication
                            ClientSecrets =
                            {
                                new Secret("secret".Sha256())
                            },
 
  
                            // scopes that client has access to
                            AllowedScopes = { "api1" }
                        }
                    };
        }
    }
} 
 public void ConfigureServices(IServiceCollection services)
        {
            // configure identity server with in-memory stores, keys, clients and resources
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients());
            services.AddMvc();
        }                  

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();
            app.UseMvc((route) => {
                route.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }

        被请求资源服务器

               (1)为webapi增加identityserver4.accesstokenvalidation包

                    (2) 配置

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthorization();
            services.AddAuthentication("Bearer")
          .AddIdentityServerAuthentication(options =>
          {
              options.Authority = "http://localhost:64433"; //授权服务器
              options.RequireHttpsMetadata = false;

              options.ApiName = "api1";
          });
        }


 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
           var log=     LoggerFac.CreateLogger<Startup>();
            log.LogInformation("infomation");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseAuthentication();   //使用认证
             app.UseHttpsRedirection();
            app.UseMvc();
        }

 

       客户端:从代码中可以看出,分两步,第一步获取token

                    ,第二部根据token去访问需要的服务。

 

using System;
using System.Net.Http;
using IdentityModel.Client;
using IdentityServer4;
using Newtonsoft.Json.Linq;

namespace Walt.Freamwork.Sec.Client
{
    class Program
    {
        static  void Main(string[] args)
        {
            var disco =  DiscoveryClient.GetAsync("http://localhost:64433/").Result;
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }


            // request token
            var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse =  tokenClient.RequestClientCredentialsAsync("api1").Result;

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);

            // call api
            var client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);

            var response =  client.GetAsync("http://localhost:50403/api/identity").Result;
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content =  response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(JArray.Parse(content));
            }


            Console.ReadKey();
        }
    }
}
 
 

       运行情况:咱们为webapi定义一个api

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Walt.Freamwork.Sec
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class IdentityController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }
    }
}

image

如果不带token

using System;
using System.Net.Http;
using IdentityModel.Client;
using IdentityServer4;
using Newtonsoft.Json.Linq;

namespace Walt.Freamwork.Sec.Client
{
    class Program
    {
        static  void Main(string[] args)
        {
            var disco =  DiscoveryClient.GetAsync("http://localhost:64433/").Result;
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }


            // request token
            var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse =  tokenClient.RequestClientCredentialsAsync("api1").Result;

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);

            // call api
            var client = new HttpClient();
           // client.SetBearerToken(tokenResponse.AccessToken);   这块注释掉了

            var response =  client.GetAsync("http://localhost:50403/api/identity").Result;
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content =  response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(JArray.Parse(content));
            }


            Console.ReadKey();
        }
    }
}
 
 

image

 

总结:本实例使用的是声明的方式认证,也可以使用用户名密码。 identityserver4是个功能强大但是使用很简洁的一个认证框架,

也支持OAUTH为外部认证提供支持,这里就不讨论了。

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/ck0074451665/p/10129829.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java Persistence API (JPA)时,可以按照以下步骤进行操作: 1. 首先,在你的项目中添加JPA的依赖。可以在pom.xml文件中添加以下代码: ```xml <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>版本号</version> </dependency> ``` 2. 创建一个实体类,该实体类对应数据库中的一张表。例如,创建一个名为User的实体类: ```java import javax.persistence.*; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String username; private String password; // getters and setters } ``` 3. 在配置文件中配置数据库连接信息。例如,在application.properties文件中添加以下代码: ```properties # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root ``` 4. 在Repository层中定义一个接口,继承JpaRepository。例如,创建一个名为UserRepository的接口: ```java import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Integer> { } ``` 5. 在Service层中使用UserRepository进行数据库操作。例如,在UserService中注入UserRepository,并调用相应的方法: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public Optional<User> getUserById(Integer id) { return userRepository.findById(id); } public User addUser(User user) { return userRepository.save(user); } public User updateUser(User user) { return userRepository.save(user); } public void deleteUser(Integer id) { userRepository.deleteById(id); } } ``` 以上就是使用JPA的基本操作步骤,通过继承JpaRepository接口,可以实现常见的数据库操作方法。你可以根据具体的需求进行扩展和定制。希望可以帮到你!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值