要实现仅允许特定域用户访问Web服务器,通常涉及以下几个基础概念和技术:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate(options =>
{
options.Events = new NegotiateEvents
{
OnAuthenticationFailed = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
}
};
});
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'your-secret-key';
app.post('/login', (req, res) => {
const user = { id: 1, username: 'exampleUser' };
const token = jwt.sign(user, secretKey, { expiresIn: '1h' });
res.json({ token });
});
app.get('/protected', verifyToken, (req, res) => {
jwt.verify(req.token, secretKey, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
res.json({ message: 'Protected content', authData });
}
});
});
function verifyToken(req, res, next) {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearerToken = bearerHeader.split(' ')[1];
req.token = bearerToken;
next();
} else {
res.sendStatus(403);
}
}
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
原因:
解决方法:
原因:
解决方法:
Authorization: Bearer <token>
)。通过以上方法和步骤,可以有效实现仅允许特定域用户访问Web服务器的目标。
领取专属 10元无门槛券
手把手带您无忧上云