我正在为移动应用程序构建 api,并使用 JWT 来验证用户身份。我正在尝试在 Laravel 5.1 中实现它。
我不断收到错误:{"error":"user_not_found"}每当我使用身份验证方法给我的令牌时。
我的过程:
Auth::attempt($credentials)$user = User::where('user_id', Auth::user()->user_id)->first();使用以下方式为用户设置令牌
$token = "";
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
Run Code Online (Sandbox Code Playgroud)它使用此方法返回一个令牌:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOm51bGwsImlzcyI6Imh0dHA6XC9cL3BlZGxyLmRldlwvYXBpXC9sb2dpbiIsImlhdCI6MTQ0OTk2NDQ2NywiZXhwIjoxNDQ5OTY4MDY3LCJuYmYiOjE0NDk5NjQ0NjcsImp0aSI6IjJlMDMyMjA5MjMyZWM1MDVlY2I3YzE4ODFjNDk1MzFmIn0.tbO_fv4WDQ6WgiHtyYJAq2rjnOtaYPq85VO2ja2YVzw
Run Code Online (Sandbox Code Playgroud)
但是当尝试使用令牌对用户进行身份验证时,它会抛出错误{"error":"user_not_found"}。
我的routes.php:
Route::any('/login', ['as' => 'login', …Run Code Online (Sandbox Code Playgroud) 我正在尝试为我的微服务生成 JWT 令牌。该令牌将使用我的前端应用程序进行服务访问。在这里,我通过添加我的用户名来设置主题。我需要添加用户 ID 和用户名。下面的代码我用于通过仅添加主题“用户名”来生成令牌。
我的代码是,
protected String getToken(String encodedSecret, Users jwtUser){
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setSubject(jwtUser.getUsername())
.signWith(SignatureAlgorithm.HS512, encodedSecret)
.compact();
}
Run Code Online (Sandbox Code Playgroud)
这里我需要添加两个主题用户名和用户ID。我如何在这里添加两个主题?
我正在 GET 请求的请求标头中将 Firebase JWT 添加到我的 Google App Engine Go 服务。这是 JavaScript:
const response = await fetch(
'https://some-app.appspot.com/_ah/data', {
method: 'get',
headers: {
'Authorization': 'Bearer ' + await Component.fetchJWT()
}
});
Run Code Online (Sandbox Code Playgroud)
在端点托管的 Go 服务上,收到请求。但是,抛出错误:
error verifying ID token: illegal base64 data at input byte 0
以下是我处理 JWT 的方式:
func (ma *myapp) SomeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
reqToken := r.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer")
reqToken = splitToken[1]
fmt.Println(reqToken) // Prints the token correctly
lib.VerifyIDToken(ma.fbapp, reqToken) // Error is thrown …Run Code Online (Sandbox Code Playgroud) 我使用 ASP.NET Core 2.1 和 JwtBearer 方案进行身份验证,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
// my options here
});
}
Run Code Online (Sandbox Code Playgroud)
非常标准,但是我遇到的问题是我的令牌权限发现端点需要授权才能访问。我需要做的是将基本身份验证标头注入到 JWT 中间件对我的权限端点执行的请求中。我正在查看配置选项,但没有看到任何允许我执行此操作的内容。我还在查看源代码,看看是否可以看到 http 请求是在哪里发出的,但它通过抽象和扩展方法非常混乱,我还没有找到它。
有人能告诉我是否可以在某个地方设置它,或者我是否必须创建自己的授权处理程序并手动将它们绑定在一起?任何建议表示赞赏。
I\xe2\x80\x99m 尝试将承载令牌添加到我的 POST 路由中。当我通过 Postman 提交 POST 请求时,我\xe2\x80\x99m 得到以下输出:
\n\n{\n "success": true,\n "token": "Bearer undefined"\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是我的 user.js 代码:
\n\nrouter.post("/login", (req, res) => {\n const email = req.body.email;\n const password = req.body.password;\n\n //find user by email\n User.findOne({ email }).then(user => {\n //check for user\n if (!user) {\n return res.status(404).json({ email: "user not found" });\n }\n //check password\n bcrypt.compare(password, user.password).then(isMatch => {\n if (isMatch) {\n //user matched\n const payload = { id: user.id, name: user.name, avatar: user.avatar }; //create …Run Code Online (Sandbox Code Playgroud) 使用LexikJWTAuthenticationBundle,可以验证控制器内传递的令牌吗?
ps 我知道$this->getUser()如果用户已通过身份验证,我可以返回用户,null否则。但这不是我所追求的。
我想知道是否有某种东西isTokenValid('the-token-string');可以给出真/假响应?
我用 jwt 加 oauth2 (在内存中)实现了 spring boot。
这里的令牌位于内存中而不是数据库中。
但是当我使用时tokenStore.findTokensByClientId(clientId),它在下面的情况下返回空白数组
例子
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIEN_ID = "vishvas-client";
static final String CLIENT_SECRET = "$2a$10$kfH4W.jyBuqvX5TLu.OfbOEUtScm4V9FEUDvGI8AWPaqObUOQ7HJ2"; // vishvas-secret
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS …Run Code Online (Sandbox Code Playgroud) 在我的 SignalR 身份验证原型中,JS 客户端没有 Context.UserIdentifier,当连接到 JS 客户端的 SignalR 集线器时,connectionId 将为 0。它与 .NET 客户端配合良好。
想知道构建连接是否错误?这是我的连接:
state.connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub", {
accessTokenFactory: async () => {
axios.post('https://localhost:44384/api/account/token', { email: email, password: password })
.then(async (response) => {
if (typeof response === 'undefined') {
return;
}
else {
console.log(response.data);
console.log(state.connection.id);
return response.data;
}
})
.catch((error) => {
console.log(error);
});
}
})
.build();
Run Code Online (Sandbox Code Playgroud)
WPF 客户端使用以下代码可以很好地连接令牌:
_connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44384/ChatHub", options =>
{
options.AccessTokenProvider = async () =>
{
var tokenUserCommand = new …Run Code Online (Sandbox Code Playgroud) 我是 Rails 和 React 新手,这可能是一个简单的问题,但我似乎无法弄清楚。
我正在尝试使用 ruby on Rails 和 React 作为客户端来实现简单的 jwt 身份验证。我按照以下建议的步骤进行操作: https://www.pluralsight.com/guides/token-based-authentication-with-ruby-on-rails-5-api
它在我的本地系统上按预期工作,但是当我将应用程序上传到heroku时,它总是返回错误:500。所有其他“发布”和“获取”请求正常工作。仅当我尝试进行身份验证并取回 auth_token 时,才会遇到 500 错误。
这是请求格式帖子:localhost:3001/api/authenticate
与身体:
{
"email": "evin@xyz.com",
"password": "evin"
}
Run Code Online (Sandbox Code Playgroud)
我通过使用 get 来验证这些数据在 heroku 上是否可用,效果非常好。
我已经花了两天多的时间来解决这个问题。网上有关此身份验证的信息非常少。有很多关于使用 auth0 的建议。但我在这种形式的身份验证方面找不到太多帮助。
这就是我所拥有的
#Path: /app/controllers/application_controller.rb
class ApplicationController < ActionController::API
before_action :authenticate_request
attr_reader :current_user
private
def authenticate_request
@current_user = AuthorizeApiRequest.call(request.headers).result
render json: { error: 'Not Authorized' }, status: 401 unless @current_user
end
end
#Path: app/controllers/api/authentication_controller.rb
class Api::AuthenticationController < ApplicationController
skip_before_action :authenticate_request
def authenticate
command = AuthenticateUser.call(params[:email], params[:password]) …Run Code Online (Sandbox Code Playgroud) 语法错误,意外的“解析器”(T_STRING),需要函数(T_FUNCTION)或常量(T_CONST)”,“异常”:“ParseError”,供应商/lcobucci/jwt/src/Configuration.php”,“行”:22
我安装了 PHP 8.0 和 composer v2.0。
该项目在本地使用 xampp 完美运行,但在 Ubuntu 20.04、Digtalocean 上的 nginx 配置中显示此错误
jwt ×10
asp.net-core ×2
c# ×2
php ×2
.net-core ×1
bcrypt-ruby ×1
bearer-token ×1
express ×1
go ×1
heroku ×1
java ×1
javascript ×1
laravel ×1
laravel-5.1 ×1
laravel-8 ×1
node.js ×1
oauth-2.0 ×1
ruby ×1
signalr ×1
spring-boot ×1
symfony ×1