我想获取属于一个特殊用户的数据。如果用户未被授权,我想返回Unauthorized()。我该怎么做呢?
这是我当前的代码(目前完全没有用户处理):
public async Task<IActionResult> GetById(int id, string token)
{
if (!ModelState.IsValid)
return BadRequest();
var entity = await Context.Set<T>().FindAsync(id).ConfigureAwait(false);
if (entity == null)
return NotFound();
return Ok(entity);
}
实体在数据库中与用户有关系。并且用户具有属性“ JwtToken”。因此,entity.User.JwtToken是可以做到的。
参数“令牌”是一个jwtToken,作为GET请求中的标头传递。
答案 0 :(得分:1)
检查custom authorization policies。您可以创建一个自定义策略并继续执行。
另一方面,您可以使用jwt令牌,而无需将其存储到任何数据库中。考虑以下示例:microsoft dev blogs
然后在您的代码中,您可以执行以下操作:
export class MyComponent implements OnInit, OnDestroy {
unsubscriber$ = new Subject<void>();
constructor(public store: Store<State>) {}
ngOnInit() {
this.store
.pipe(select(selectRouteParams), takeUntil(this.unsubscriber$))
.subscribe(params => {
// reload data
// this code is being run even when this component is being navigated away from
});
}
ngOnDestroy() {
this.unsubscriber$.next();
this.unsubscriber$.complete();
}
}
您无权访问呼叫而不是数据。数据对您来说不存在。如果您未经授权返回,则让攻击者知道数据已存在,以便他们枚举系统中的数据。