radi0
@radi0

Spring Security, обработка exception в UserDetailsService

В данный момент пытаюсь заставить работать Spring Security с Mongodb. И все работает, кроме того, что если пользователь отсутствует в базе, вместо сообщения об этом вываливается exception 500 (AuthenticationServiceException), который я, собственно, и вызываю.
В случае успешного совпадения имени пользователя и пароля переходим по default-target-url,
если совпадает только имя, по authentication-failure
Во всех примерах, которые я смотрел, конструкция именно такая, подскажите где я ошибаюсь (или как верно словить exception, мне кажется что это должно быть проще чем явно их ловить?).

(gist для этих файлов)

Переопределение UserDetailsService:

@Service
public class MongoUserDetailsService implements UserDetailsService {

	@Override
	public UserDetails loadUserByUsername(String username) throws AuthenticationServiceException {
		MongoOperations mongoOperations = null;
		
		try {
			mongoOperations = new MongoTemplate(new Mongo(), "mydb");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
		try {
			
			Query query = new Query(Criteria.where("email").is(username));
			System.out.println("query ready to go");
			Customer customer = mongoOperations.findOne(query, Customer.class);
			System.out.println("query done");
			if (customer == null){
				throw new AuthenticationServiceException("Authentication failed for user " + username);

			}
			boolean enabled = true;
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;

			return new User(
					customer.getUsername(), 
					customer.getPassword().toLowerCase(),
					enabled,
					accountNonExpired,
					credentialsNonExpired,
					accountNonLocked,
					getAuthorities(2));

		} catch (Exception e) {
			System.out.println("query failed");
			throw new RuntimeException(e);
		}
	}

	public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
		return authList;
	}


	public List<String> getRoles(Integer role) {
		List<String> roles = new ArrayList<String>();

		if (role.intValue() == 1) {
			roles.add("ROLE_USER");
			roles.add("ROLE_ADMIN");

		} else if (role.intValue() == 2) {
			roles.add("ROLE_USER");
		}

		return roles;
	}

	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
		}
		return authorities;
	}
}


и security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
  <http access-denied-page="/error403.jsp">
    <intercept-url pattern="/index*" access="ROLE_USER,ROLE_ANONYMOUS"/>
    <intercept-url pattern="/add*" access="ROLE_USER"/>
    <intercept-url pattern="/delete/*" access="ROLE_ADMIN"/>
    <form-login login-page="/login.jsp" default-target-url="/index" authentication-failure-url="/login.jsp?error=true"/>
    <logout logout-url="/logout" logout-success-url="/index"/>
    <anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>
    <remember-me user-service-ref="userDetailsService"/>
</http>
<authentication-manager>
    <authentication-provider user-service-ref="mongoUserDetailsService"/>
</authentication-manager>
<beans:bean id="mongoUserDetailsService" class="com.company.testproj.utils.MongoUserDetailsService"/>
</beans:beans>
  • Вопрос задан
  • 3848 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы