我正在尝试使用django-rest-framework在我的Django REST API中实现基于Auth0 JWT的身份验证.我知道有一个可用于REST框架的JWT库,我尝试使用它,因为官方的Auth0 twitter帐户提到它应该与auth0 + Django一起使用.
编辑:我正在使用官方auth0 python api指南为此代码.它是为烧瓶而写的,但我想我可以将它移植到Django,因为它们的工作方式类似.
现在,这并没有解决我想要的问题,因此我正在尝试login_required为视图编写自己的decorater.我在这里的代码如下:
def auth_required(f):
def wrap(request, *args, **kwargs):
auth = request.META.get('HTTP_AUTHORIZATION', None)
if not auth:
return authenticate({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'})
parts = auth.split()
if parts[0].lower() != 'bearer':
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'})
elif len(parts) == 1:
return authenticate({'code': 'invalid_header', 'description': 'Token not found'})
elif len(parts) > 2:
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s …Run Code Online (Sandbox Code Playgroud) 我想将auth0.com与开源解析服务器结合使用.
我目前的方法是通过iOS的Lock库使用标准登录从auth0获取令牌.使用该令牌,我想在我的解析服务器上调用一个自定义身份验证方法,该方法检查令牌是否有效以及是否将登录用户.
我的问题是几乎没有关于为parse-server编写自定义oauth的文档.
到目前为止,我有自定义身份验证的代码.
var Parse = require('parse/node').Parse;
function validateAuthData(authData, options) {
console.log('validateAuthData()');
return new Promise((resolve, reject) => {
try {
var decoded = jwt.verify(authData.access_token, opions.sharedSecret);
if (authData.id === decoded.sub) {
resolve({});
}
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Unauthorized');
} catch(e) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, e.message);
}
});
}
function validateAppId(appIds, authData) {
console.log('validateAppId()');
return Promise.resolve();
}
module.exports = {
validateAppId: validateAppId,
validateAuthData: validateAuthData
};
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用,我也不明白如何使用此代码来验证特定用户.解析服务器是否进行数据库查找以将特定身份验证数据与特定用户相匹配?另外,如何使用自定义身份验证注册新用户.当用户尝试登录但在我的解析数据库中它还不存在时会发生什么?
另一种似乎是这个,使用规则的auth0.com.有什么区别以及该规则将如何运作?我对身份验证,oauth和jwt的经验很少.
最后,我使用它从我的iOS客户端调用我的自定义身份验证.然而,这也不起作用,但我不确定它是由于iOS部分还是因为我的自定义身份验证尚未运行.
总而言之,我遇到了一些看似相当容易的问题.我想使用auth0作为我的身份验证提供程序,我想整合它是解析服务器,因为我非常感谢解析和客户端sdk的便利性.我相当肯定有更多的人有类似的问题,但是我没有找到任何关于如何正确执行此操作的明确资源.
更多链接
我在我的网站上显示一些从节点服务器返回的数据.它一直运作到今天.现在,当我访问我的网页时,我的服务器控制台上出现了以下错误.我Auth0用于登录用户.
UnauthorizedError: invalid algorithm
at C:\workspace\New\MyApp\node_modules\express-jwt\lib\index.js:100:22
at C:\workspace\New\MyApp\node_modules\express-jwt\node_modules\jsonwebtoken\index.js:155:18
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
Run Code Online (Sandbox Code Playgroud)
可能是什么问题?
我创建了一个Auth0客户端,我正在登录并收到此令牌:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1rVkdOa1l5T1VaQ1JqTkRSVE5EUmtNeU5rVkROMEUyUTBVMFJrVXdPVEZEUkVVNU5UQXpOZyJ9.eyJpc3MiOiJodHRwczovL3RvdGFsY29tbW56LmF1LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwMzI5NzA4OTYyMTk5NjUwMjY2MiIsImF1ZCI6ImxTWUtXMUZZdENkMWJLQmdXRWN0MWpCbmtDU3R2dW5SIiwiaWF0IjoxNTA5ODYyMTI1LCJleHAiOjE1MTAyMjIxMjV9.kjmckPxLJ4H9R11XiBBxSNZEvQFVEIgAY_jj2LBy4sEJozBB8ujGE7sq9vEIjMms-Lv2q9WzFQPrqcxyBcYC4Je4QojMgvqLDCodtpot0QUle8QfGmonc1vZYIZyX-wqyOXtRqhoZVEKTeLhm9Le2CV4_a3BwgjkE1LjcDx01GZfsnaId8mh10kGk-DBmr5aVc8MxglLCq5Uk8Zbl2vDc__UMDgx1eQPQg-zve4fUf8zHcxizypYTnF_v0dEAT00L2j5J41SFYdWvP6ReQ3vhVYew2o9iM6u1s75HE-xW8s4pzV4BZAQtgfgIeCd6aVGZs76bcnQXBLej1B7zaPBvA
Run Code Online (Sandbox Code Playgroud)
我现在要做的是使用jsonwebtoken验证令牌.令牌使用RS256算法进行签名.
我将签名证书下载为a .pem并且我成功使用它来验证令牌,如下所示:
var cert = fs.readFileSync('certificate.pem');
jwt.verify(token, cert, {algorithm: 'RS256'}, (err, decoded) => {
console.log(err)
console.log(decoded)
});
Run Code Online (Sandbox Code Playgroud)
我想要做的是它不起作用是使用秘密验证令牌(在Auth0客户端设置中称为客户端密钥,并且是一个字符串).
jwt.verify(token, MYSECRET, {algorithm: 'RS256'}, (err, decoded) => {
console.log(err)
console.log(decoded)
});
Run Code Online (Sandbox Code Playgroud)
此代码始终抛出错误:
{ JsonWebTokenError: invalid algorithm
at Object.module.exports [as verify] (C:\code\aws\learn-authorizer\node_modules\jsonwebtoken\verify.js:90:17)
at Object.<anonymous> (C:\code\aws\learn-authorizer\testme.js:25:5)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3 name: 'JsonWebTokenError', message: …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个 NestJS 项目,该项目使用 Auth0 进行身份验证,并带有passport-jwt库(与 结合使用@nestjs/passport),但我无法使其正常工作。我不确定我哪里出错了。我一遍又一遍地阅读文档,但仍然找不到问题。
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
import { xor } from 'lodash';
import { JwtPayload } from './interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: 'http://localhost:3000',
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
});
}
validate(payload: …Run Code Online (Sandbox Code Playgroud) 描述 我试图在打字稿项目中使用 jwt-decode,即 Stencil 项目 & 它抛出以下错误:
此表达式不可调用。Type '{ default: (token: string, options?: Options) => TTokenDto; }' 没有调用签名。
import * as jwt_decode from 'jwt-decode';
.
.
.
let token = "........";
let decoded = jwt_decode(token);
Run Code Online (Sandbox Code Playgroud)
再生产
在我们的代码中,我们使用外部 SDK 来登录用户 (Auth0)。此 SDK 使用意图打开 WebView ACTION_VIEW。
我试图重写我们已有的一些自动化测试(在此切换之前我们使用本机登录)。WebView 正确打开,但是当我尝试使用androidx.test.espresso:espresso-web代码与其交互时onWebView().forceJavascriptEnabled()
,出现以下错误:
androidx.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1841)
at androidx.test.espresso.base.EspressoExceptionHandler.handleSafely(EspressoExceptionHandler.java:2)
at androidx.test.espresso.base.EspressoExceptionHandler.handleSafely(EspressoExceptionHandler.java:1)
at androidx.test.espresso.base.DefaultFailureHandler$TypedFailureHandler.handle(DefaultFailureHandler.java:4)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:5)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:8)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:11)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:8)
at androidx.test.espresso.web.sugar.Web$WebInteraction.forceJavascriptEnabled(Web.java:1)
Run Code Online (Sandbox Code Playgroud)
相反,如果我不使用forceJavascriptEnabled(),并直接尝试使用 访问 WebView onWebView().withElement(),则会收到错误:
androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: an instance of android.webkit.WebView and webView.getSettings().getJavaScriptEnabled() is <true>
View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=1080, height=2400, …Run Code Online (Sandbox Code Playgroud) 目前,当我创建路由时,我会检查 Auth0 方法 - isAuthenticated() - 以确定是否返回受保护的页面或重定向到登录。但是,此状态仅存在于内存中,并且不会在浏览器刷新时将用户保留在其页面上,我希望这样做。
这是一个 React/RR4/React Context 应用程序,我的 Auth0 方法列在 Auth.js(如下)中。
将登录状态存储在 localStorage 中是非常不可取的。如果我将 Auth0 令牌存储在 cookie 中,我不确定如何验证令牌,因为没有设置服务器验证。检查将启用安全数据持久性的正确条件是什么?
ProtectedRoutes.jsx:
<Route
exact
key={route.path}
path={route.path}
render={() => (
// CONDITION TO CHECK
context.auth.isAuthenticated()
? (
<div>
<route.component />
</div>
) : <Redirect to="/login" />
)}
/>
Run Code Online (Sandbox Code Playgroud)
Auth.js(添加以供参考):
import auth0 from 'auth0-js';
import authConfig from './auth0-variables';
class Auth {
accessToken;
idToken;
expiresAt;
tokenRenewalTimeout;
auth0 = new auth0.WebAuth({
domain: authConfig.domain,
clientID: authConfig.clientId,
redirectUri: authConfig.callbackUrl,
responseType: 'token id_token',
scope: 'openid'
});
constructor() …Run Code Online (Sandbox Code Playgroud) 我在我的电子应用程序中使用 auth0 身份验证。无论如何,我都没有使用电子应用程序的浏览器窗口。所以,我想在外部浏览器(chrome、Firefox 等)或安装的默认浏览器中打开我的 auth0 身份验证窗口。有什么办法吗?
我正在使用 Expo 的AuthSession模块登录 Auth0:
let result = await AuthSession.startAsync({
authUrl: `${auth0Domain}/authorize?` + qs.stringify({
client_id: auth0ClientId,
response_type: 'code',
scope: 'openid profile email offline_access',
redirect_uri: redirectUrl,
code_challenge_method: 'S256',
code_verifier: codeVerifier,
state: oAuthState,
audience: auth0Audience
})
})
if (result.type === 'success') {
...
} else if (
result.type === 'dismiss' ||
(result.type === 'error' && result.errorCode === 'login-declined')
) {
// FIXME: alert never pops without delay here, despite the if correctly evaluating true
// Any way to check if the …Run Code Online (Sandbox Code Playgroud) auth0 ×10
jwt ×4
node.js ×2
oauth ×2
typescript ×2
android ×1
cookies ×1
django ×1
electron ×1
expo ×1
express-jwt ×1
gui-testing ×1
ios ×1
nestjs ×1
parse-server ×1
passport.js ×1
python ×1
react-native ×1
reactjs ×1
rest ×1
webview ×1