如何在envoy中提取jwt ,并将提取的值放入标头
我需要在 http_filters 下面添加一些额外的属性,但我对此一无所知,并且我研究了jwtProvider和jwtHeader,它们都出现在 envoy 文档中
这是我的envoy.yaml文件,此配置有什么问题:
admin:
access_log_path: "/dev/null"
address:
socket_address:
address: 0.0.0.0
port_value: 8001
static_resources:
listeners:
- name: main
address:
socket_address:
address: 0.0.0.0
port_value: 1337
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
codec_type: AUTO
route_config:
name: local_route
virtual_hosts:
- name: local_service
domains:
- "*"
routes:
- match:
prefix: "/"
route:
host_rewrite_literal: 0.0.0.0
cluster: web_service
http_filters:
- name: config.filter.http.jwt_authn.v2alpha.JwtHeader
from_params:
- jwt_token
- …Run Code Online (Sandbox Code Playgroud) String prvKey = "-----BEGIN PRIVATE KEY-----\n"
+ "........\n"
+ "-----END PRIVATE KEY-----";
Jwts.builder()
.setClaims(jwtClaim)
.signWith(SignatureAlgorithm.RS256, prvKey)
.compact();
Run Code Online (Sandbox Code Playgroud)
Running this Java code prints
java.lang.IllegalArgumentException: Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.
当我将RS256更改为HS256签名时,令牌生成良好,但我的目标服务器只接受RS256签名令牌,所以我必须使用RS256。
错误日志对我没有帮助,因为我已经在使用signWith(SignatureAlgorithm, Key)方法了。
我该如何解决这个问题?
任何评论、链接都值得赞赏。
我在后端使用 ASP.NET Core Web API,并在 Blazor WASM 客户端的 httpClient 标头中使用 JWT 令牌(我不在 cookie 中存储 JWT 令牌)。
问题是,虽然用户已登录并且身份验证和授权工作没有问题,但在每个控制器(继承自ControllerBase)中始终:
HttpContext.User.Identity.IsAuthenticated是假的HttpContext.User.Identity.Name一片空白HttpContext.User.Claims一片空白但请求具有 JWT 令牌(Request.Headers["Authorization"][0]等于Bearer eyJhbGciOiJIUzI1...)并且[Authorize]属性正常工作。
这是我的startup.cs的样子:
services.AddIdentity()
services.AddSingleton<IAuthorizationPolicyProvider, AuthorizeExPolicyProvider>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
ClockSkew = TimeSpan.Zero
});
services.AddAuthorization(options =>
{
});
Run Code Online (Sandbox Code Playgroud)
我还按正确的顺序调用了中间件:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); …Run Code Online (Sandbox Code Playgroud) 当我使用以下代码创建令牌时,我尝试在 CI4 中使用 JWT 创建一个 Restful api:
$key = getenv('TOKEN_SECRET');
$payload = array(
"iat" => 1356999524,
"nbf" => 1357000000,
"uid" => $user['id'],
"email" => $user['email']
);
$token = JWT::encode($payload, $key);
Run Code Online (Sandbox Code Playgroud)
为什么我会收到错误:
预计有 3 个参数。找到 2
我有一个 Keycloak 领域,其中一些用户作为 Nodejs + Typescript 项目的 IdP。
如果我按“全部注销”,它们就会从这里消失,但它们仍然有效。
例子:
1) I create a new session. I get its JWT token as a response
2) I do a GET req on one of the protected routes with the token attached. It works.
4) I logout all sessions by pressing the button in that photo
5) I do the same GET req on the same protected route. It still works.
I expect it NOT to work, because I previously logged …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 JWT 不记名令牌和谷歌身份验证来实现对 Web API 的身份验证。发现这个答案非常有帮助,但是当它成功验证时,我得到 500,但有以下例外:
System.NullReferenceException:未将对象引用设置为对象的实例。在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:错误:执行请求时发生未处理的异常。
System.NullReferenceException:未将对象引用设置为对象的实例。在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() 在 Microsoft.AspNetCore.Authentication.AuthenticationService .AuthenticateAsync(HttpContext 上下文,字符串方案) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)
当令牌无效时,我会收到 401 响应。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.SecurityTokenValidators.Clear();
o.SecurityTokenValidators.Add(
new GoogleTokenValidator(
client_id
));
});
services.AddScoped<PhotoService>();
services.AddScoped<TagService>();
services.AddScoped(_ => new BlobServiceClient(Configuration.GetConnectionString("AzureBlobStorage")));
services.AddDbContext<Data.DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers().AddJsonOptions(options =>
{ …Run Code Online (Sandbox Code Playgroud) 我正在使用 React 和 Next.js 开发一个 Web 应用程序,并且我还有一个作为后端分离的 Node.js API。
我有一个登录表单,我将数据发送到 API 以恢复 JWT,当我这样做时,一切正常,但在将用户重定向到受保护的路由“仪表板”后,或者刷新后,用户上下文会丢失。
这是受保护的路线:
import React, {useContext, useEffect} from 'react'
import { useRouter } from "next/router";
import { Context } from '../../context/context';
export default function DashboardIndexView() {
const router = useRouter();
const {isUserAuthenticated, setUserToken, userToken} = useContext(Context);
useEffect(() => {
isUserAuthenticated()
? router.push("/dashboard")
: router.push("/authentication/admin");
}, []);
return (
<>
<h1>Dashboard index view</h1>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
这是上下文文件:
import React, {createContext, useEffect, useState} from 'react'
import { useRouter } from "next/router"; …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 django JWT 令牌构建用户身份验证应用程序,当我尝试测试我的用户身份验证 api 并验证password和 时password2,它会生成以下错误:
TypeError: User() got unexpected keyword arguments: 'password2'
Run Code Online (Sandbox Code Playgroud)
我serializers.py的如下:
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.get('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def validate_data(self, validate_data):
return User.objects.create_user(**validate_data)
Run Code Online (Sandbox Code Playgroud)
我的views.py如下:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import …Run Code Online (Sandbox Code Playgroud) 我应该在 pom.xml 中添加哪个 Maven 依赖项来解决这些错误: -SignatureException 无法解析为类型 -ExpiredJwtException 无法解析为类型 -UnsupportedJwtException 无法解析为类型
有人可以解释一下在 Java 应用程序中使用 UsernamePasswordAuthenticationToken 的以下代码吗?
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null,
userDetails == null ?
List.of() : userDetails.getAuthorities()
);
Run Code Online (Sandbox Code Playgroud)
我试图了解此代码中如何使用 UsernamePasswordAuthenticationToken 来处理身份验证,特别是关于 userDetails 参数和作为凭据传递的空值。我也对使用 List.of() 和 userDetails.getAuthorities() 来设置权限感到好奇。任何见解都会有帮助。谢谢你!
jwt ×10
c# ×2
spring-boot ×2
asp.net-core ×1
bearer-token ×1
codeigniter ×1
django ×1
envoyproxy ×1
jjwt ×1
keycloak ×1
maven ×1
next.js ×1
node.js ×1
php ×1
python ×1
reactjs ×1