我有一个.p12证书文件,我使用SSL转换器将其转换为.pem证书文件.然后我在我的android代码中使用那个pem证书文件,如下所示:
OkHttpClient okHttpClient = new OkHttpClient();
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.pem_certificate);
Certificate ca;
ca = cf.generateCertificate(instream);
KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(kStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (CertificateException
| KeyStoreException
| NoSuchAlgorithmException
| IOException
| KeyManagementException e) {
e.printStackTrace();
}
baseURL = endpoint;
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(baseURL)
.setClient(new OkClient(okHttpClient))
.build();
service = restAdapter.create(DishService.class);
Run Code Online (Sandbox Code Playgroud)
但是这段代码不起作用.它在"ca = cf.generateCertificate(instream);"行中失败了.使用CertificateException消息.
我使用express-jwt保护我的API端点,以便只有经过身份验证的用户才能访问我的API.现在我也想根据用户的角色保护我的API.例如,如果用户是管理员,则用户只能访问某些API,如果他们是超级管理员,则只能访问其他API等.如何实现此目的?我在express-jwt github doc中找到了这段代码:
app.get('/protected',
jwt({secret: 'shhhhhhared-secret'}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
Run Code Online (Sandbox Code Playgroud)
看起来这段代码正在API控制器功能中进行授权.这是唯一的推荐方式吗?有没有更好的方法来做到这一点?有关此最佳做法的任何建议吗?