问题描述
UsuarioModel类
public class UsuarioModel
{
public int CodUsuario { get; set; }
public string Nome { get; set; }
public string Senha { get; set; }
public string Telefone { get; set; }
public DateTime DataRegisto { get; set; }
public bool Estado { get; set; }
public int CodPerfil { get; set; }
}
public async Task<string> LoginAsync(string nome,string senha)
{
var keyvalues = new List<keyvaluePair<string,string>>
{
new keyvaluePair<string,string>("username",nome),new keyvaluePair<string,string>("password",senha),string>("grant_type","password")
};
var request = new HttpRequestMessage(HttpMethod.Post,Constants.BaseApiAddress + "token");
request.Content = new FormUrlEncodedContent(keyvalues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsstringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
var accesstokenExpiration = jwtDynamic.Value<DateTime>(".expires");
var accesstoken = jwtDynamic.Value<string>("access_token");
Settings.AccesstokenExpirationDate = accesstokenExpiration;
Debug.WriteLine(accesstokenExpiration);
Debug.WriteLine(content);
return accesstoken;
}
通过生成访问令牌,此方法可以正常工作。但是我的问题是:我如何获得接收访问令牌的用户的“ CodPerfil”值,以验证应该定向到的菜单?
public class Loginviewmodel : Baseviewmodel
{
private readonly ApiServices _apiServices = new ApiServices();
public string Nome { get; set; }
public string Senha { get; set; }
public ICommand LoginCommand
{
get
{
return new Command(async () =>
{
var accesstoken = await _apiServices.LoginAsync(Nome,Senha);
Settings.Accesstoken = accesstoken;
Login();
});
}
}
public async void Login()
{
var usuario = new UsuarioModel
{
Nome = Nome,Senha = Senha,CodPerfil = CodPerfil
};
Settings.CodPerfil = CodPerfil;
if (CodPerfil == 1)
{
App.Current.MainPage = new MenuMorador();
}
else
{
App.Current.MainPage = new MenuRecolhedor();
}
}
public Loginviewmodel()
{
Nome = Settings.Nome;
Senha = Settings.Senha;
}
当我通过断点执行此方法时,“ CodPerfil”变量没有收到任何值。问题是:如何接收与已注册用户相关联的“ CodPerfil”属性的值,以便在接收访问令牌后验证他们将定向到的菜单?
启动课程
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
public void ConfigureAuth(IAppBuilder app)
{
//this is very important line cross orgin source(CORS)it is used to enable cross-site HTTP requests
//For security reasons,browsers restrict cross-origin HTTP requests
app.UseCors(CorsOptions.AllowAll);
var OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,TokenEndpointPath = new PathString("/token"),AccesstokenExpireTimeSpan = TimeSpan.FromDays(10),//token expiration time
Provider = new OauthProvider()
};
app.USEOAuthBearerTokens(OAuthOptions);
app.USEOAuthAuthorizationServer(OAuthOptions);
app.USEOAuthBearerAuthentication(new OAuthBearerAuthenticationoptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);//register the request
}
}
OauthProvider类
public class OauthProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
await Task.Run(() => context.Validated());
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
using (var db = new DataContext2())
{
if (db != null)
{
var user = db.Usuario.Where(o => o.Nome == context.UserName && o.Senha == context.Password).FirstOrDefault();
if (user != null)
{
identity.AddClaim(new Claim(ClaimTypes.Role,user.CodPerfil.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Name,user.Nome));
identity.AddClaim(new Claim("LoggedOn",DateTime.Now.ToString()));
await Task.Run(() => context.Validated(identity));
}
else
{
context.SetError("Wrong Crendtials","Provided username and password is incorrect");
}
}
else
{
context.SetError("Wrong Crendtials","Provided username and password is incorrect");
}
return;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)