我已经配置了一个安全拦截器,它应该让我在这里注入的用户会话对象(这是一个单例):
public DependencyInjection extends AbstractModule{
//Class that has AccessLevel Annoation
bind(InterfaceA.class).to(ImplA.class);
bind(UserPersistor.class).to(UserPersistorImpl.class);
//My session that I wish to inject
bind(UserSession.class).to(UserSessionHandler.class);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AccessLevel.class),
new SecurityInterceptor(getProvider(UserSession.class)));
}
这是我的UserSessionHandler:
@Singleton
public class UserSessionHandler implements UserSession {
private UserLevel userLevel = UserLevel.DEFAULT;
private final UserPersistor userPersistor;
@Inject
public UserSessionHandler(UserPersistor userPersistor) {
this.userPersistor = userPersistor;
}
@Override
public boolean loginUser(String userName, String password) {
Benutzer user = userPersistor.getUserByName(userName);
if (user == null) {
return false;
} else {
if (user.getKennwort().equals(password)) {
userLevel = UserLevel.valueOf(user.getRolleId().getBezeichnung().toUpperCase());
return true;
} else {
return false;
}
}
}
@Override
public boolean logoutUser() {
userLevel = UserLevel.DEFAULT;
return true;
}
@Override
public UserLevel getUserLevel() {
return userLevel;
}
}
这里SecurityInterceptor目前的样子如下:
@Singleton
public class SecurityInterceptor implements MethodInterceptor {
private final Provider<UserSession> session;
@Inject
public SecurityInterceptor(Provider<UserSession> session){
this.session = session;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
AccessLevel[] acessRoles = invocation.getMethod().getAnnotationsByType(AccessLevel.class);
List<UserLevel> allowedRoles = new ArrayList<>();
for(AccessLevel accessRole: acessRoles){
allowedRoles.add(accessRole.value());
}
//Make sure that User has one of the allowed Access-Levels
if (!allowedRoles.contains(session.get().getUserLevel())) {
throw new InvalidAccessException("No Access allowed with userlevel" + session.get().getUserLevel());
}
return invocation.proceed();
}
}
现在我设法让它在我的Mockito-Test中运行,绑定到这样的实例:
bind(MockInterface.class).to(MockClass.class);
bind(UserSession.class).toInstance(user);
bind(UserPersistor.class).toInstance(mockUserPersistor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AccessLevel.class),
new SecurityInterceptor(getProvider(UserSession.class)));
但是我不想自己创建一个实例,但希望曾经有一个guice正在创建。我怎么能这样做,或者我目前做错了什么?
编辑:我的主要问题是,用户似乎与生成的用户不同。这是一个简单的例子:
Injector injector = Guice.createInjector(new DependencyInjection());
UserSession session = injector.createInstance(UserSession.class);
InterfaceA methodCaller = injector.createInstance(InterfaceA.class);
if(session.loginUser("a","b")){
System.out.println(session.getUserLevel().toString()); //Returns Admin
}
methodCaller.callMethodWithAnnotation();
现在,当我检查拦截器中的session.getUserLevel时,我得到“默认”
EDIT2:我的endgoal是在我的拦截器和我使用UserSession的任何地方拥有相同的会话实例