@AuthenticationPrincipal返回null问题

时间:2018-04-24 13:47:23

标签: java spring authentication spring-security

当我使用

CustomUserDetails customUser = (CustomUserDetails) 
SecurityContextHolder.getContext().getAuthentication().getPrincipal();

虽然有效但

@AuthenticationPrincipal返回null 为什么?我怎么解决这个问题?

CustomUserDetailsS​​ervice

 package com.sencerseven.blog.model;



import java.io.Serializable;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.sencerseven.blogbackend.dto.User;
import com.sencerseven.blogbackend.service.UserService;

@Service
public class CustomUserDetailsService implements UserDetailsService,Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = userService.getByEmail(username);
        if(user == null) {
            return null;
        }

        user.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

        CustomUserDetails userDetails = user.map(CustomUserDetails::new).get();

        return userDetails;
    }



    }

CustomUserDetails

   package com.sencerseven.blog.model;

import java.io.Serializable;
import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.sencerseven.blogbackend.dto.User;

public class CustomUserDetails extends User implements UserDetails,Serializable {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public CustomUserDetails() {
        // TODO Auto-generated constructor stub
    }

    public CustomUserDetails(final User user) {
        super(user);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole())).collect(Collectors.toList());
    }

    @Override
    public String getUsername() {
        // TODO Auto-generated method stub
        return super.getEmail();
    }


    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return super.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

}

WebSecurityConfig

  package com.sencerseven.blog.config;


        import javax.sql.DataSource;

        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.core.annotation.Order;
        import org.springframework.security.authentication.AuthenticationManager;
        import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
        import org.springframework.security.config.annotation.web.builders.HttpSecurity;
        import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
        import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
        import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
        import org.springframework.security.oauth2.provider.ClientDetailsService;
        import org.springframework.security.oauth2.provider.approval.ApprovalStore;
        import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
        import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
        import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
        import org.springframework.security.oauth2.provider.token.TokenStore;
        import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

        import com.sencerseven.blog.model.CustomUserDetailsService;
        import com.sencerseven.blogbackend.service.UserService;

        @Configuration
        @EnableWebSecurity
        public class WebSecurityConfig{


            @Bean
            public static BCryptPasswordEncoder bCryptPasswordEncoder(){
                return new BCryptPasswordEncoder();
            }


            @Configuration
            @Order(1)
            public static class AdminLoginConfig extends WebSecurityConfigurerAdapter{  
                @Autowired
                DataSource dataSource;

                @Override
                protected void configure(AuthenticationManagerBuilder auth) throws Exception {

                    auth.jdbcAuthentication().dataSource(dataSource)
                    .usersByUsernameQuery("Select email,password,enabled from User where role='ADMIN' and email = ? ")
                    .authoritiesByUsernameQuery("Select email, role from User where email = ?").passwordEncoder(bCryptPasswordEncoder());
                }

                @Override
                protected void configure(HttpSecurity http) throws Exception {

                    http
                    .authorizeRequests().antMatchers("/admin/login").permitAll().and()
                    .antMatcher("/admin/**").authorizeRequests().anyRequest().hasAuthority("ADMIN")
                    .and()
                    .formLogin().loginPage("/admin/login").usernameParameter("email").passwordParameter("password").defaultSuccessUrl("/admin",
    true).loginProcessingUrl("/admin/login")
                    .and()
                    .logout()
                    .and()
                    .exceptionHandling().accessDeniedPage("/").and().csrf();

                }
            }

            @Configuration
            @Order(2)
            public static class ApiLoginConfig extends WebSecurityConfigurerAdapter{    
                @Autowired
                DataSource dataSource;

                @Autowired
                ClientDetailsService clientDetailsService;




                 @Override
                    protected void configure(HttpSecurity http) throws Exception {
                        http.csrf().disable().antMatcher("/oauth/token").authorizeRequests().anyRequest().permitAll();


                    }


                    @Autowired
                    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
                        auth.jdbcAuthentication().dataSource(dataSource)
                        .usersByUsernameQuery("Select user_name,password,enabled from User where user_name = ? ")
                        .authoritiesByUsernameQuery("Select user_name, role from User where user_name = ?").passwordEncoder(bCryptPasswordEncoder());
                    }



                @Override
                @Bean
                public AuthenticationManager authenticationManagerBean() throws Exception {
                    return super.authenticationManagerBean();
                }

                @Bean
                public TokenStore tokenStore() {
                    return new InMemoryTokenStore();
                }

                @Bean
                @Autowired
                public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
                    TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
                    handler.setTokenStore(tokenStore);
                    handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
                    handler.setClientDetailsService(clientDetailsService);
                    return handler;
                }

                @Bean
                @Autowired
                public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
                    TokenApprovalStore store = new TokenApprovalStore();
                    store.setTokenStore(tokenStore);
                    return store;
                }
            }


            @Configuration
            public static class HomeLoginConfig extends WebSecurityConfigurerAdapter{       

                @Autowired
                UserService userService;

                @Autowired
                private CustomUserDetailsService customUserDetailsService;


                @Override
                protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                    auth.userDetailsService(customUserDetailsService).passwordEncoder(bCryptPasswordEncoder());



                    /*
                     auth.jdbcAuthentication().dataSource(dataSource)
                    .usersByUsernameQuery("Select email,password,enabled from User where email = ? ")
                    .authoritiesByUsernameQuery("Select email, role from User where email = ?").passwordEncoder(bCryptPasswordEncoder());
                    */
                }


                @Override
                protected void configure(HttpSecurity http) throws Exception {

                    http.csrf().disable();
                    http.authorizeRequests().antMatchers("/profile").hasAnyAuthority("ADMIN","USER").and()
                    .authorizeRequests()
                    .antMatchers("/**").permitAll().and()
                    .formLogin().loginPage("/login").usernameParameter("email").passwordParameter("password").defaultSuccessUrl("/",
    true).loginProcessingUrl("/login")
                    .and()
                    .logout()
                    .and()
                    .exceptionHandling().accessDeniedPage("/w");



                }
            }




        }

相关课程HomeloginConfig

页面控制器

@RequestMapping(value = {"/","/index","/home"})
public ModelAndView indexPage(@AuthenticationPrincipal CustomUserDetails customUserDetails) {
    ModelAndView mv = new ModelAndView("page");

    mv.addObject("title", "home");
    mv.addObject("userClickHomePage",true);

    System.out.println("tessttt!!!--> " + customUserDetails);
    List<CategoryModel> categoryModelList = new ArrayList<CategoryModel>();

    List<Category> categories = categoryService.allCategoryWithLimitedPosts(5, 0);

    List<Posts> posts = postService.getSliderPost(0, 5);

    List<Posts> featuredPost = postService.featuredPost(0,10);



    for(Category tempCategory : categories) {
        CategoryModel categoryModel = new CategoryModel();
        categoryModel.setCategory(tempCategory);
        categoryModel.setPopulerPosts(postService.getTrendPosts(6, 0, tempCategory.getId()));
        categoryModelList.add(categoryModel);
    }



    if(categories != null) {
        mv.addObject("categoryModelList", categoryModelList);
    }
    mv.addObject("featuredPosts", featuredPost);
    mv.addObject("sliderPosts", posts);

    String pass = bcryptPasswordEncoder.encode("123");
    System.out.println(pass);
    return mv;
}

@AuthenticationPrincipal CustomUserDetails返回null为什么?

但是SecurityContextHolder.getContext()。getAuthentication.getPrincipal 返回CustomUserDetails它工作正常

为什么@AuthenticationPrincipal不起作用?

  

如果我没有登录网站,则抛出异常

     

java.lang.ClassCastException:java.lang.String无法在sun.reflect的com.sencerseven.blog.controller.PostController.postPage(PostController.java:63)中强制转换为com.sencerseven.blog.model.CustomUserDetails。 at.MativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method .java:498)

代码行是

后置控制器

CustomUserDetails customUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

0 个答案:

没有答案