Y
Y
Yuri2017-01-18 23:10:04
Java
Yuri, 2017-01-18 23:10:04

How to get the logged in user in Spring Security?

When I try to get a logged in user, I get an exception: : Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.security.service.UserDetailsServiceImpl. How to fix it?
Try example:
UserDetailsServiceImpl userDetailsService = (UserDetailsServiceImpl)org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Git link: https://github.com/YuriyKlepka/website

Answer the question

In order to leave comments, you need to log in

7 answer(s)
A
Alexander Kuznetsov, 2017-01-19
@MoonMay

For example, something like this (a piece of code from the controller):

// check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ((!(auth instanceof AnonymousAuthenticationToken)) && auth != null) {
  UserDetails userDetail = (UserDetails) auth.getPrincipal();

  if (userDetail != null) {
    model.addObject("username", userDetail.getUsername());
  } else {
    model.addObject("username", "");
  }
}
,
In the security config there is this:
<authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="usersManager">
            <password-encoder hash="bcrypt"/>
        </authentication-provider>
    </authentication-manager>

The usersManager is declared in the application context config:
<bean id="usersManager" class="org.whatever.impl.UsersServiceImpl">
        <property name="usersDAO" ref="usersDAO"/>
        <property name="languageDao" ref="languagesDAO"/>
        <property name="roleDAO" ref="roleDAO"/>
        <property name="usersViewDAO" ref="usersViewDAO"/>
</bean>

Well, the UsersServiceImpl itself looks like this:
package org.whatever.impl;
/*импорты убрал */
/* интерфейс UsersService наследует org.springframework.security.core.userdetails.UserDetailsService */
public class UsersServiceImpl extends ServiceBase implements UsersService {

    @Autowired
    private UsersDAO usersDAO;

    public void setUsersViewDAO(UsersViewDAO usersViewDAO) {
        this.usersViewDAO = usersViewDAO;
    }

    public UsersDAO getUsersDAO() {
        return usersDAO;
    }

  /*сократил код*/

    /**
     * Детали по пользователю, полученному из базы
     */
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User userFromDb = this.getUsersDAO().getUserByLogin(login);

        if (userFromDb != null) {
            return new org.whatever.UserView(userFromDb); /*применяет org.springframework.security.core.userdetails.UserDetails*/
        }

        String result = new Formatter().format("User with login %s not found", login).toString();
        throw new UsernameNotFoundException(result);
    }
}

A
aol-nnov, 2017-01-18
@aol-nnov

> userdetails.User cannot be cast to com.security.service.UserDetailsServiceImpl
how to fix? do not cast to incompatible types.
and get the user (by the way, where?)
Here, in the controller, for example, you can do this:

@RequestMapping(...)
public String someController(Model m, @Value("#{T(org.springframework.security.core.context.SecurityContextHolder).context.authentication}") Authentication auth) {
}

but in your code
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
which, in principle, is the same thing ...
what then is the question ?!

X
xmoonlight, 2017-07-23
@DaniLaFokc

It's more correct to draw everything in a vector (SVG) and then add other DOM objects (or bitmaps, for example, a logo).

A
Alexander Tokmakov, 2017-07-23
@calliko

Wouldn't a png image work?

T
tema_sun, 2017-07-23
@tema_sun

The picture looks like a vector. So why not use svg?

V
ValeraValera, 2017-07-23
@cluberr

Determine the absolute coordinates and radius of each circle, determine the gradients, shadows and stacking order, arrange the circles, colorize, determine the z-indices, the main block, make the overflow hayden...

T
twobomb, 2017-07-23
@twobomb

Canvas seems to me the easiest and performance is normal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question