天道酬勤

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" });

 

posted @ 2019-07-11 17:02  JulyLuo  阅读(430)  评论(0编辑  收藏  举报