各位好:
用spring boot 和spring spring security做用户权限认证,想要自己重新实现登录和认证部分功能,所以自己写了AuthenticationProvider这块,但是现在发现在AuthenticationProvider里出现NullPointerException情况,具体如下:
1、如果使用的service类不包含其他的注入的话,就可以正常执行。
2、如果使用的service类A 还注入引用了B类,这样的话,执行A类的方法就会报空指针。
例如:result类又注入了demo类,在执行result.get_context()的时候,就会空指针
@Service
public class demo {
public String get_string()
{
return "get_string";
}
}
@Service
public class result {
@Autowired
demo dd;
private static result resu ;
public String get_context()
{
return dd.get_string();
}
public String get_result()
{
return "get_result";
}
public void init()
{
resu = this;
resu.dd = this.dd;
}
}
@Autowired
MyAuthenticationProvider myAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/user/login*","/user/register","/js/**","/css/**","/img/**","/font-awesome/**","/test/**").permitAll() //指定那些URL不要被保护
.antMatchers("/admin/**").hasRole("admin")//
.antMatchers("/user/**").hasRole("users")//
.antMatchers("/guest/**").hasRole("guest")//
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/user/login") //登录的时候你要跳转到哪里
.failureUrl("/user/login") //失败页面
.defaultSuccessUrl("/index/index")
// .and().sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry)
.permitAll() //登录任意访问
.and()
.rememberMe() //rememberMe
.and() //注销行为任意访问
.logout()
.logoutUrl("/user/logout")
.logoutSuccessUrl("/index/logout") // 注销成功后的 url
.and()
.csrf() //关闭csrf 不然不支持post
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(myAuthenticationProvider);
}
package com.moxi.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.moxi.serviceImpl.User.UserServiceImpl;
import com.moxi.serviceImpl.User.result;
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
result result;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
System.out.println("start is authenticate");
result ss = new result();
try
{
System.out.println(ss.get_context());
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
public boolean supports(Class<?> authentication) {
System.out.println("start supports");
System.out.println("authentication= "+authentication.getClass().getName());
return true;
}
}
Spring Security
Spring Boot