Basic authentication Dropwizard:BasicAuth
使用 我想根据数据库用户(UserDAO)检查凭据 我得到以下例外 !!org.hibernate.HibernateException:当前没有绑定到的会话 执行上下文 如何将会话绑定到身份验证器? 还是有更好的方法来检查数据库用户 验证器类Basic authentication Dropwizard:BasicAuth,basic-authentication,dropwizard,Basic Authentication,Dropwizard,使用 我想根据数据库用户(UserDAO)检查凭据 我得到以下例外 !!org.hibernate.HibernateException:当前没有绑定到的会话 执行上下文 如何将会话绑定到身份验证器? 还是有更好的方法来检查数据库用户 验证器类 package com.example.helloworld.auth; import com.example.helloworld.core.User; import com.example.helloworld.db.UserDAO; import
package com.example.helloworld.auth;
import com.example.helloworld.core.User;
import com.example.helloworld.db.UserDAO;
import com.google.common.base.Optional;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {
UserDAO userDAO;
public ExampleAuthenticator(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
Optional<User> user;
user = (Optional<User>) this.userDAO.findByEmail(credentials.getUsername());
if ("secret".equals(credentials.getPassword())) {
return Optional.of(new User(credentials.getUsername()));
}
return Optional.absent();
}
}
package com.example.helloworld.auth;
导入com.example.helloworld.core.User;
导入com.example.helloworld.db.UserDAO;
导入com.google.common.base.Optional;
导入io.dropwizard.auth.AuthenticationException;
导入io.dropwizard.auth.Authenticator;
导入io.dropwizard.auth.basic.BasicCredentials;
公共类ExampleAuthenticator实现验证器{
UserDAO UserDAO;
公共示例验证器(UserDAO UserDAO){
this.userDAO=userDAO;
}
@凌驾
公共可选身份验证(BasicCredentials凭据)引发AuthenticationException{
可选用户;
user=(可选)this.userDAO.findByEmail(credentials.getUsername());
if(“secret”.equals(credentials.getPassword())){
返回可选的.of(新用户(credentials.getUsername());
}
返回可选的。缺席();
}
}
应用程序类
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
final UserDAO userDAO = new UserDAO(hibernate.getSessionFactory());
environment.jersey().register(new AuthDynamicFeature(
new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(new ExampleAuthenticator(userDAO))
.setAuthorizer(new ExampleAuthorizer())
.setRealm("SUPER SECRET STUFF")
.buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class);
//If you want to use @Auth to inject a custom Principal type into your resource
environment.jersey().register(new AuthValueFactoryProvider.Binder(User.class));
environment.jersey().register(new UserResource(userDAO));
@覆盖
公共void运行(HelloWorldConfiguration,Environment)引发异常{
final UserDAO UserDAO=new UserDAO(hibernate.getSessionFactory());
environment.jersey().register(新AuthDynamicFeature)(
新建BasicCredentialAuthFilter.Builder()
.setAuthenticator(新示例Authenticator(userDAO))
.setAuthorizer(新示例Authorizer())
.setRealm(“超级秘密的东西”)
.buildAuthFilter());
environment.jersey().register(RolesAllowedDynamicFeature.class);
//如果要使用@Auth将自定义主体类型注入到资源中
register(新的AuthValueFactoryProvider.Binder(User.class));
register(newuserresource(userDAO));
在应用程序
类中需要如下代码
environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(
new ExampleAuthenticator(userDAO), "AUTHENTICATION", User.class)));
environment.jersey().register(AuthFactory.binder)(新BasicAuthFactory(
新的示例验证器(userDAO),“AUTHENTICATION”,User.class));
然后,您可以在方法的用户
参数上使用@Auth
标记,任何传入的身份验证凭据都将点击身份验证
方法,允许您返回正确的用户
对象,或者如果凭据不在数据库中,则返回缺席
编辑:适用于Dropwizard v0.8.4要使auth与0.9+一起工作,您需要以下内容。您可以参考此特定内容作为示例 包括依赖项
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-auth</artifactId>
<version>${dropwizard.version}</version>
</dependency>
授权人
public class UserAuthorizer<P> implements Authorizer<User>{
/**
* Decides if access is granted for the given principal in the given role.
*
* @param principal a {@link Principal} object, representing a user
* @param role a user role
* @return {@code true}, if the access is granted, {@code false otherwise}
*/
@Override
public boolean authorize(User principal, String role) {
return true;
}
}
在从0.9开始的最新版本上,您可以在资源类方法中使用“@Context”注释,如下所示:
@RolesAllowed("EMPLOYEE")
@Path("/emp")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getEmployeeResponse(@Context SecurityContext context) {
SimplePrincipal sp = (SimplePrincipal) context.getUserPrincipal();
return Response.ok("{\"Hello\": \"Mr. " + sp.getUsername() + "\"( Valuable emp )}").build();
}
谢谢Rohan,但这不适用于Dropwizard 0.9.0-rc4。@DanielOzean啊,我明白了。这应该适用于Dropwizard 0.8.4,这是最新的官方版本。在正式发布之前,您可能不想使用0.9.0进行开发。请注意,这个问题涉及到rc 0.9.0-rc4。与0.9.1.1.Final的问题相同
public class UnAuthorizedResourceHandler implements UnauthorizedHandler {
@Context
private HttpServletRequest request;
@Override
public Response buildResponse(String prefix, String realm) {
Response.Status unauthorized = Response.Status.UNAUTHORIZED;
return Response.status(unauthorized).type(MediaType.APPLICATION_JSON_TYPE).entity("Can't touch this...").build();
}
@Context
public void setRequest(HttpServletRequest request) {
this.request = request;
}
}
public class UserAuthorizer<P> implements Authorizer<User>{
/**
* Decides if access is granted for the given principal in the given role.
*
* @param principal a {@link Principal} object, representing a user
* @param role a user role
* @return {@code true}, if the access is granted, {@code false otherwise}
*/
@Override
public boolean authorize(User principal, String role) {
return true;
}
}
@GET
public Response hello(@Auth User user){
return Response.ok().entity("You got permission!").build();
}
@RolesAllowed("EMPLOYEE")
@Path("/emp")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getEmployeeResponse(@Context SecurityContext context) {
SimplePrincipal sp = (SimplePrincipal) context.getUserPrincipal();
return Response.ok("{\"Hello\": \"Mr. " + sp.getUsername() + "\"( Valuable emp )}").build();
}