spring boot jpaboot badcredentialsexception 怎么返回到页面

Java Code Examples of org.springframework.security.authentication.BadCredentialsException
Java Code Examples for org.springframework.security.authentication.BadCredentialsException
The following code examples are extracted from open source projects. You can click
vote up the examples that are useful to you.
From project spring-security-samples-securemail, under directory
/src/main/java/org/springframework/security/samples/mail/security/.
Source file:
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token=(UsernamePasswordAuthenticationToken)
MailUser user=this.userRepository.findUserByEmail(token.getName());
if (user == null) {
if (!user.getPassword().equals(token.getCredentials())) {
throw new BadCredentialsException("Username / Password was not found");
return new UsernamePasswordAuthenticationToken(user,user.getPassword(),AuthorityUtils.createAuthorityList("ROLE_USER"));
From project caseconductor-platform, under directory
/utest-services-impl/src/main/java/com/utest/service/security/.
Source file:
private User login(final String email,final String password){
if ((email == null) || (email.length() == 0) || (password == null)|| (password.length() == 0)) {
throw new BadCredentialsException(BAD_CREDENTIALS);
final User user=userService.getUserByEmail(email);
if (user == null) {
throw new BadCredentialsException(BAD_CREDENTIALS);
if (!EncodeUtil.encode(password).equals(user.getPassword())) {
throw new BadCredentialsException(BAD_CREDENTIALS);
verifyUser(user);
From project ehour, under directory
/eHour-service/src/main/java/net/rrm/ehour/user/service/.
Source file:
@Override @Transactional public void changePassword(String username,String currentPassword,String newUnencryptedPassword) throws BadCredentialsException {
User user=userDAO.findByUsername(username);
Validate.notNull(user,String.format("Can't find user with username %s",username));
String encryptedCurrentPassword=encryptPassword(currentPassword,user.getSalt());
if (!user.getPassword().equals(encryptedCurrentPassword)) {
throw new BadCredentialsException("Invalid current password");
changePassword(user,newUnencryptedPassword);
From project excilys-bank, under directory
/excilys-bank-web/src/main/java/com/excilys/ebi/bank/web/controller/.
Source file:
private Message handleException(Exception loginException){
if (loginException instanceof BadCredentialsException) {
return new Message("message.error.login.badCredentials");
Throwable cause=ExceptionUtils.getRootCause(loginException);
return new Message("message.error.login",cause != null ? cause.getMessage() : loginException.getMessage());
From project greenhouse, under directory
/src/main/java/com/springsource/greenhouse/account/.
Source file:
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token=(UsernamePasswordAuthenticationToken)
Account account=accountRepository.authenticate(token.getName(),(String)token.getCredentials());
return authenticatedToken(account,authentication);
SignInNotFoundException e) {
throw new org.springframework.security.core.userdetails.UsernameNotFoundException(token.getName(),e);
InvalidPasswordException e) {
throw new BadCredentialsException("Invalid password",e);
From project spring-security, under directory
/cas/src/main/java/org/springframework/security/cas/authentication/.
Source file:
private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
final Assertion assertion=this.ticketValidator.validate(authentication.getCredentials().toString(),getServiceUrl(authentication));
final UserDetails userDetails=loadUserByAssertion(assertion);
userDetailsChecker.check(userDetails);
return new CasAuthenticationToken(this.key,userDetails,authentication.getCredentials(),authoritiesMapper.mapAuthorities(userDetails.getAuthorities()),userDetails,assertion);
final TicketValidationException e) {
throw new BadCredentialsException(e.getMessage(),e);
From project spring-security-kerberos, under directory
/spring-security-kerberos-core/src/main/java/org/springframework/security/extensions/kerberos/.
Source file:
public String validateTicket(byte[] token){
String username=
username=Subject.doAs(this.serviceSubject,new KerberosValidateAction(token));
PrivilegedActionException e) {
throw new BadCredentialsException("Kerberos validation not succesfull",e);
From project spring-security-oauth, under directory
/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/client/filter/.
Source file:
@Override public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
OAuth2AccessToken accessToken=restTemplate.getAccessToken();
OAuth2Authentication result=tokenServices.loadAuthentication(accessToken.getValue());
InvalidTokenException e) {
throw new BadCredentialsException("Could not obtain user details from token",e);
From project uaa, under directory
/common/src/main/java/org/cloudfoundry/identity/uaa/scim/.
Source file:
private void checkPasswordMatches(String id,String oldPassword){
String currentP
currentPassword=jdbcTemplate.queryForObject(READ_PASSWORD_SQL,new Object[]{id},new int[]{Types.VARCHAR},String.class);
IncorrectResultSizeDataAccessException e) {
throw new ScimResourceNotFoundException("User " + id + " does not exist");
if (!passwordEncoder.matches(oldPassword,currentPassword)) {
throw new BadCredentialsException("Old password is incorrect");
Example 10
From project Axon-trader, under directory
/web-ui/src/main/java/org/axonframework/samples/trader/webui/security/.
Source file:
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
UsernamePasswordAuthenticationToken token=(UsernamePasswordAuthenticationToken)
String username=token.getName();
String password=String.valueOf(token.getCredentials());
FutureCallback&UserAccount& accountCallback=new FutureCallback&UserAccount&();
AuthenticateUserCommand command=new AuthenticateUserCommand(username,password.toCharArray());
commandBus.dispatch(new GenericCommandMessage&AuthenticateUserCommand&(command),accountCallback);
account=accountCallback.get();
if (account == null) {
throw new BadCredentialsException("Invalid username and/or password");
InterruptedException e) {
throw new AuthenticationServiceException("Credentials could not be verified",e);
ExecutionException e) {
throw new AuthenticationServiceException("Credentials could not be verified",e);
UsernamePasswordAuthenticationToken result=new UsernamePasswordAuthenticationToken(account,authentication.getCredentials(),userAuthorities);
result.setDetails(authentication.getDetails());
Example 11
From project GNDMS, under directory
/gndms/src/de/zib/gndms/gndms/security/.
Source file:
@Override public UserDetails loadUserDetails(final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken) throws UsernameNotFoundException {
String dn=(String)preAuthenticatedAuthenticationToken.getPrincipal();
if (GridMapUserDetailsService.searchInGridMapfile(allowedHostsFileName,dn)) {
if (reverseDNSTest)
if (!reverseDNSLookup(X509DnConverter.openSslDnExtractCn(dn),preAuthenticatedAuthenticationToken.getDetails())) {
("Host-CN revers DNS lookup failed for: " + dn);
throw new BadCredentialsException("Host-CN reverse DNS lookup failed.");
UnknownHostException e) {
throw new BadCredentialsException("",e);
GNDMSUserDetails userDetails=new GNDMSUserDetails();
userDetails.setAuthorities(Collections.&GrantedAuthority&emptyList());
userDetails.setDn(dn);
userDetails.setIsUser(false);
return userD
final SecurityContext context=SecurityContextHolder.getContext();
if (context != null && context.getAuthentication() != null) {
final Object principal=context.getAuthentication().getPrincipal();
if (principal instanceof GNDMSUserDetails) {
final GNDMSUserDetails gndmsUserDetails=(GNDMSUserDetails)
if (gndmsUserDetails.isUser())
if (!dn.equals(gndmsUserDetails.getUsername()))
throw new UsernameNotFoundException("Certificate vs HttpHeader: dn mismatch ('" + dn + "' vs. '"+ gndmsUserDetails.getUsername()+ "'.");
return userDetailsService.loadUserByUsername(dn);
IOException e) {
throw new RuntimeException(e);
Example 12
From project OpenTripPlanner, under directory
/opentripplanner-web-utils/src/main/java/org/opentripplanner/web/authentication/.
Source file:
private Authentication makeAuthRequest(HttpServletRequest request){
String wsseHeader=request.getHeader("X-WSSE");
if (wsseHeader == null) {
throw new BadCredentialsException("No wsse header");
String[] tokenParts=wsseHeader.split(", ");
if (tokenParts.length != 4) {
throw new BadCredentialsException("Wrong number of parts (expected 4 got " + tokenParts.length + ")");
String[] method_username=tokenParts[0].split(" ");
if (method_username.length != 2 || !method_username[0].equals("UsernameToken")) {
throw new BadCredentialsException("Not UsernameToken");
HashMap&String,String& params=parse_params(method_username[1],tokenParts[1],tokenParts[2],tokenParts[3]);
if (params == null) {
throw new BadCredentialsException("Bogus params");
return new WSSEAuthentication(params.get("Username"),params.get("PasswordDigest"),params.get("Nonce"),params.get("Created"));
Example 13
From project sched-assist, under directory
/sched-assist-war/src/main/java/org/jasig/schedassist/web/security/.
Source file:
* Incorporates some of the
(non-Javadoc)
* @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
@Override protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String username=authentication.getName();
String password=(String)authentication.getCredentials();
if (logger.isDebugEnabled()) {
logger.debug("Processing authentication request for user: " + username);
if (!StringUtils.hasLength(username)) {
throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.emptyUsername","Empty Username"));
Assert.notNull(password,"Null password was supplied in authentication token");
DirContextOperations userData=getAuthenticator().authenticate(authentication);
if (userData == null) {
throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.badCredentials","Bad credentials"));
PasswordPolicyException ppe) {
throw new LockedException(messages.getMessage(ppe.getStatus().getErrorCode(),ppe.getStatus().getDefaultMessage()));
UsernameNotFoundException notFound) {
if (hideUserNotFoundExceptions) {
throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.badCredentials","Bad credentials"));
throw notF
Example 14
From project ManalithBot, under directory
/ManalithBotConsole/src/main/java/org/manalith/ircbot/console/.
Source file:
private void sendMessage(String target,String message){
remoteService.sendMessage(target,message);
BadCredentialsException e) {
System.out.println("????? ?????? ??????.");
Logger.getLogger(Launcher.class).error(e);
Example 15
From project More-Vaadin, under directory
/springsecurity-integration/src/main/java/com/morevaadin/vaadin7/springsecurity/.
Source file:
@Subscribe public void login(LoginEvent event){
AuthenticationService authHandler=new AuthenticationService();
authHandler.handleAuthentication(event.getLogin(),event.getPassword(),RequestHolder.getRequest());
navigator.navigateTo(MAIN_VIEW_NAME);
BadCredentialsException e) {
Notification.show("Bad credentials",TYPE_ERROR_MESSAGE);
Example 16
From project opencit, under directory
/ui/web/src/test/java/org/openengsb/opencit/ui/web/.
Source file:
private void mockAuthentication(){
AuthenticationManager authManager=mock(AuthenticationManager.class);
final Collection&GrantedAuthority& authorities=new ArrayList&GrantedAuthority&();
authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer&Authentication&(){
@Override public Authentication answer(
InvocationOnMock invocation){
Authentication auth=(Authentication)invocation.getArguments()[0];
if (auth.getCredentials().equals("password")) {
return new UsernamePasswordAuthenticationToken(auth.getPrincipal(),auth.getCredentials(),authorities);
throw new BadCredentialsException("wrong password");
appContext.putBean("authenticationManager",authManager);
Example 17
From project randi2, under directory
/src/main/java/de/randi2/utility/listener/.
Source file:
@Override public void beforePhase(final PhaseEvent arg0){
Exception e=(Exception)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
if (e instanceof BadCredentialsException || e instanceof LockedException) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY,null);
Randi2.showMessage(e.getMessage());
Example 18
From project rolefen, under directory
/src/main/java/ru/ics2/rolefen/model/dao/.
Source file:
public boolean setCurrentUser(String login,String password){
Authentication request=new UsernamePasswordAuthenticationToken(login,password);
Authentication result=authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
BadCredentialsException e) {
Example 19
From project saiku, under directory
/saiku-core/saiku-web/src/main/java/org/saiku/web/service/.
Source file:
public void authenticate(HttpServletRequest req,String username,String password){
UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(username,password);
token.setDetails(new WebAuthenticationDetails(req));
Authentication authentication=this.authenticationManager.authenticate(token);
log.debug("Logging in with [{}]",authentication.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(authentication);
BadCredentialsException bd) {
throw new RuntimeException("Authentication failed for: " + username,bd);Suppose I have simple bean, which can authenticate user by password and also know roles of any specified user:
interface MyBeanInterface {
boolean check(String username, String password);
List&String& roles(String username);
What is the simplest way to plug this functionality into Spring web application with basic HTTP security?
Simultaneously, I would like to annotate my controllers and service methods with @Secured annotation only. No any dot-separated predicates , please.
I can't break through that numerous "populators", "managers", "adapters" and other "configurers" in Spring Security API...
1) A Greeting class to return from controller
2) A GreetingController class to serve web requests /greeting1 and /greeting2. I annotated first method with @Secured({"USER", "ADMIN"}) and the second with @Secured({"ADMIN"}).
3) I wrote MyAuthService where I authenticated two user with different level of access.
4) I wrote AuthenticationProviderEx where implemented authenticate() method with calling MyAuthService bean.
5) I wrote SecurityConfig bean with configure() returning my provider.
The code is . In this state it does not asking authentication at all.
I have added @EnableGlobalMethodSecurity(securedEnabled = true) to SecurityConfig class and it started to ask username and password, but, unfortunately, returns error 403 on any request.
解决方案 Make a custom authentication provider wrapper around your interface, something like:
@Component("customAuthenticationProvider")
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private MyBeanInterface myI
public Authentication authenticate(Authentication authentication) {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
if (!myInterface.check(username, password)) {
throw new BadCredentialsException("Bad username or password.");
List&GrantedAuthority& authorities = new ArrayList&&();
for (String role : myInterface.roles(username)) {
authorities.add(new SimpleGrantedAuthority(role));
return new UsernamePasswordAuthenticationToken(username, password, authorities);
public boolean supports(Class&?& clazz) {
return UsernamePasswordAuthenticationToken.class.equals(clazz);
And use it in your security config, with XML:
&authentication-manager&
&authentication-provider ref="customAuthenticationProvider"/&
&/authentication-manager&
Update: Also works with java config:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationP
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(customAuthenticationProvider);
/* rest of security config here */
The rest is pretty normal stuff.
本文地址: &
假设我有简单的bean,可以通过密码验证用户,也知道任何特定用户的角色: 接口MyBeanInterface {
布尔检查(字符串用户名,字符串密码);
清单<串GT;角色(字符串的用户名);} 什么是外挂这个功能与基本的HTTP安全春web应用程序最简单的方法?同时,我想我的注释控制器和服务方法,只有 @Secured 注释。没有任何点分隔的predicates 喜欢这里,请。我无法通过无数个“populators”破“经理人”,在春季安全API“适配器”等“configurers”...
更新 我说: 1)问候类,从控制器返回 2) GreetingController 类服务的Web请求 / greeting1 和 / greeting2 。我第一次注释方法, @Secured({“USER”,“ADMIN”}),第二个具有 @Secured({“ADMIN”}) 。 3)我写了 MyAuthService 在这里我验证的两个用户具有不同的访问级别。 4)我写了 AuthenticationProviderEx 其中实施认证()方法,调用 MyAuthService 豆。 5)我写了 SecurityConfig 豆与配置()回我人员。在code是在这里提交fdc2466 。在这种状态下,它不要求身份验证的。 更新2
我已经加入 @EnableGlobalMethodSecurity(securedEnabled = TRUE)到 SecurityConfig 类,并开始询问用户名和密码,但不幸的是,返回错误 403 上的任何请求。解决方案 请在你的界面自定义身份验证提供包装,是这样的:
@Component(“customAuthenticationProvider”)公共类CustomAuthenticationProvider实现的AuthenticationProvider {
@Autowired
私人MyBeanInterface MyInterface的;
公开验证身份验证(验证认证){
字符串username = authentication.getName();
。字符串密码= authentication.getCredentials()的toString();
如果(!myInterface.check(用户名,密码)){
抛出新BadCredentialsException(“坏用户名或密码。”);
清单<&GrantedAuthority的GT;当局=新的ArrayList<>();
对于(字符串角色:myInterface.roles(用户名)){
authorities.add(新SimpleGrantedAuthority(角色));
返回新UsernamePasswordAuthenticationToken(用户名,密码,主管部门);
公共布尔支持(类<> clazz所){
返回UsernamePasswordAuthenticationToken.class.equals(clazz所);
}} 和使用它在安全配置,使用XML: <认证经理&
<身份验证提供者REF =“customAuthenticationProvider”/>< /认证经理&
更新:同时使用Java的配置如下:
@Configuration@EnableWebMvcSecurity@EnableGlobalMethodSecurity(securedEnabled =真)公共类WebSecurityConfig扩展WebSecurityConfigurerAdapter {
@Autowired
私人CustomAuthenticationProvider customAuthenticationP
保护无效配置(AuthenticationManagerBuilder AUTH){
auth.authenticationProvider(customAuthenticationProvider);
/ *安全配置的其余部分在这里* /} 剩下的就是pretty正常的东西。
本文地址: &
扫一扫关注官方微信spring-boot教程入门2—为rest服务添加security_Java_第七城市
spring-boot教程入门2—为rest服务添加security
demo工程接上篇,本文介绍如何给rest服务添加安全机制。##加入security依赖在POM文件中添加如下依赖:``` org.springframework.boot spring-boot-starter-security``` 重新启动应用,访问http://localhost:8080/user ,会弹出要求输入用户名密码的输入框。用户名输入user,密码在输出日志里面找到这一段。 Using default security password: f03c3a81-1ba0-4e72-9f52-4d其中 f03c3a81-1ba0-4e72-9f52-4d就是密码,每次启动都会随机生成。##添加security配置自动生成的用户名密码显然不能用于生产环境,spring security也支持自定义用户账户,新建SecurityConfig类继承自WebSecurityConfigurerAdapter。###内存用户在SecurityConfig中加入以下代码。```@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("zhm").password("1q2w3e4r").roles("USER").and().withUser("admin").password("1q2w3e4r").roles("USER","ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception { // @formatter:off http.httpBasic().and().logout().and().authorizeRequests().anyRequest().fullyAuthenticated().and().csrf().disable(); // @formatter:on}``` 重启应用就可以使用zhm/1q2w3e4r或者admin/1q2w3e4r登录了。###数据库用户当然用户账户还可以基于数据库存储,具体实现如下。```package com.zhm.import com.zhm.repository.UserInfoRimport org.springframework.beans.factory.annotation.Aimport org.springframework.context.annotation.Bimport org.springframework.context.annotation.Cimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBimport org.springframework.security.config.annotation.web.builders.HttpSimport org.springframework.security.config.annotation.web.configuration.EnableWebSimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerA/** * Created by zhm on 16-10-18. */@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserInfoR@Overrideprotected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().logout().and().authorizeRequests().anyRequest().fullyAuthenticated().and().csrf().disable();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider());}public MyAuthenticationProvider authenticationProvider()throws Exception { MyAuthenticationProvider authenticationProvider = new MyAuthenticationProvider(repository); return authenticationP}}```MyAuthenticationProvider类```package com.zhm.import com.zhm.domain.UserIimport com.zhm.repository.UserInfoRimport com.zhm.utils.EncryptUimport org.springframework.security.authentication.AuthenticationPimport org.springframework.security.authentication.BadCredentialsEimport org.springframework.security.authentication.UsernamePasswordAuthenticationTimport org.springframework.security.core.Aimport org.springframework.security.core.AuthenticationEimport org.springframework.security.core.GrantedAimport java.util.HashSimport java.util.S/** * Created by zhm on 16-10-18. */public class MyAuthenticationProvider implements AuthenticationProvider {private UserInfoRepository userInfoRpublic MyAuthenticationProvider(UserInfoRepository userInfoRepository){ this.userInfoRepository = userInfoR}@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); UserInfo user = userInfoRepository.findByUsername(username); // 2. Check the passwords match. if (!user.getPassword().equalsIgnoreCase(EncryptUtils.encodeMD5String(password))) { throw new BadCredentialsException("Bad Credentials"); } // 3. Preferably clear the password in the user object before storing in authentication object user.setPassword(""); // 4. Return an authenticated token, containing user data and authorities return new UsernamePasswordAuthenticationToken(user.getUsername(), null, getAuthorities(user));}private Set getAuthorities(UserInfo user){ //可以添加用户权限 Set authorities = new HashSet();}@Overridepublic boolean supports(Class&?> authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));}}```重启应用,访问http://localhost:8080/user 输入zhm/123456就能访问接口了。##完整实例/2014th7cj/d/file/p//au0i2qwab2k
Linux-学习笔记(PHP向)&一&
最新教程周点击榜
微信扫一扫

我要回帖

更多关于 bad credential 的文章

 

随机推荐