按照春天的任何要求获取用户详细信息

时间:2018-02-19 22:16:31

标签: java spring spring-security

我想在正确登录系统后获得,以便服务/用户始终以用户登录的登录名的形式返回响应。

但是我遇到了问题,因为服务返回状态404。

弹簧控制器:

@RestController
public class UserController {

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public UserView home(@CurrentUser User principal) {
        return principal != null ? new UserView(principal) : null;
    }
}

自己的注释:

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {
}

服务:

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
private Logger logger = LoggerFactory.getLogger(getClass());

@Autowired
DataSource dataSource;

@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);
    String SQL = "select username, enabled from admin.ebpp_user where username = ?";
    User user = (User)jdbcTemplateObject.queryForObject(SQL, new Object[]{userName}, new JdbcUserMapper());
    logger.info("User: "+ user);
    return user;
}
}

映射器:

public class JdbcUserMapper implements RowMapper {
    @Override
    public Object mapRow(ResultSet resultSet, int rowNum) throws SQLException {

        return User.Builder.anUser()
                .withUsername(resultSet.getString("username"))
                .build();
    }
}

最后是主要的配置类:

  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username, password, enabled from admin.ebpp_user where username=?")
                .authoritiesByUsernameQuery("select username, authority from admin.authorities where username = ?");
    }

使用userDetailsS​​ervice登录:

2018-02-19 22:58:42,714 INFO[com.MyUserDetailsService] user: User{username='test'}

当它调用:localhost:8080 / rest / home然后收到“404 Not Found” 有谁知道为什么我不能通过该服务下载用户?

edit.1。

我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/context/applicationContext.xml</param-value>
    </context-param>
</web-app>

和applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
    <bean id="userDetailsService"
                class="com.MyUserDetailsService" />

    <jee:jndi-lookup id="dbDataSource"
                     jndi-name="java:/TestDS"
                     expected-type="javax.sql.DataSource" />

</beans>

edit.2

当我添加代码时:

 @RequestMapping(value = "/user", method = RequestMethod.GET)
    public UserView home(@CurrentUser User principal) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        // userDetail contains data

    }

然后userDetail包含数据(在调试器模式下),但“@CurrentUser User principal”jest仍为null

1 个答案:

答案 0 :(得分:2)

当您想要接收Principal时,您已将其定义为Method参数,然后按照包含在主体中的名称加载User。

@RestController
public class UserController {

  @Autowired
  MyUserDetailsService userdetailservice;

  @RequestMapping(value = "/user", method = RequestMethod.GET)
  public UserView home(Principal principal) {
      User user = userdetailservice.loadUserByUsername(principal.getName());
      return principal != null ? new UserView(user) : null;
  }
}