• ServiceStack JWT 准备


    ServiceStack JWT设置

    ServcieStack 自带的验证授权模块使用 sql server存储,所以我们第一步需要配置数据库的一些选项

    container.Register<IDbConnectionFactory>(
        new OrmLiteConnectionFactory(AppSettings.GetString("DBConn"), SqlServerDialect.Provider));
    
    container.Register<IAuthRepository>(c =>
                    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
                    {
                        UseDistinctRoleTables = true
                    });
    
    OrmLiteConfig.DialectProvider.GetStringConverter().UseUnicode = true;
    
    var authRepo = (OrmLiteAuthRepository)container.Resolve<IAuthRepository>();

    这个数据库的角色表默认是不创建的,这里设置为单独的表

    设置完毕之后,如果数据库没有配置,则可以代码中直接创建相应的表

    authRepo.InitSchema();
    

     创建之后,数据库会自动新建3个表

    表创建之后,需要插入一些数据进行测试,也可以通过代码实现:

    authRepo.CreateUserAuth(new UserAuth
    {
        DisplayName = "Credentials",
        FirstName = "First",
        LastName = "Last",
        FullName = "First Last",
        Email = "demis.bellot@gmail.com",
        UserName = "julyluoTest1"
    }, "test1");
    
    authRepo.CreateUserAuth(new UserAuth
    {
        DisplayName = "Credentials",
        FirstName = "First",
        LastName = "Last",
        FullName = "First Last",
        UserName = "julyLuoTest2"
    }, "test2");

     最后设置 JWT的验证

    Plugins.Add(new AuthFeature(() => new AuthUserSession(),
        new IAuthProvider[] {
                      
            new CredentialsAuthProvider(),
            //Use JWT so sessions survive across AppDomain restarts, redeployments, etc
            new JwtAuthProvider(AppSettings)
            {
                RequireSecureConnection = false
            },
        }));

    客户端调用

    1 获取bearToken

    var authclient = new JsonServiceClient("http://localhost:62375");
    
    var authResponse = authclient.Post(new Authenticate
    {
        provider = "credentials",
        UserName = "julyluoTest1",
        Password = "test1",
        RememberMe = true,
    });
      
    var bearToken = authResponse.BearerToken;
                  

    2 通过bearToken获取需要验证的服务

    var client = new JsonServiceClient("http://localhost:62375") { BearerToken = bearToken };
    
    var ssResponse = client.Get(new SSAuthTest() { Name = "julyLUoTest" });
  • 相关阅读:
    java垃圾回收算法和垃圾收集器
    (转)数据库ACID特性
    数据库范式
    (转)java Exception层次结构详解
    java Thread方法解析: sleep join wait notify notifyAll
    (转)java反编译i++和++i问题
    (转)git使用教程
    (转)java位运算
    (转)原码、反码、补码
    [翻译]如何编写GIMP插件(一)
  • 原文地址:https://www.cnblogs.com/julyluo/p/11171210.html
Copyright © 2020-2023  润新知