Java tutorial
/** * Atomsphere is an enterprise mobile application server. * Copyright (C) 2011 JatakaSource Ltd. * * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Atomsphere is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Atomsphere. If not, see <http://www.gnu.org/licenses/>. */ package org.atomsphere.management.authentication; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.codec.binary.Base64; import org.atomsphere.management.model.authentication.User; import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; public class AuthenticationUtils { private static final String ROLE_ADMIN = "ROLE_ADMIN"; private static final String ROLE_USER = "ROLE_USER"; public static final int SLAT_SIZE = 10; /** * Accepts list of Roles and return array[] of ACEGI GrantedAuthorityImpl */ public static Collection<GrantedAuthority> toGrantedAuthority(User user) { if (user.getAuthorities() != null && user.getAuthorities().size() > 0) { return user.getAuthorities(); } Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); if (user.isAdministrator()) { grantedAuthorities.add(new SimpleGrantedAuthority(ROLE_ADMIN)); } else { grantedAuthorities.add(new SimpleGrantedAuthority(ROLE_USER)); } return grantedAuthorities; } public static Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } // Print password example (use this method when adding new user to csv) public static void main(String[] args) { MessageDigestPasswordEncoder encoder = new ShaPasswordEncoder(); encoder.setEncodeHashAsBase64(true); System.out.println(encoder.encodePassword("password", "?")); basicAuthentication(); } /** * Output for basic authentication password, -H example * -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" */ public static void basicAuthentication() { String credentials = String.format("%s:%s", "admin", "password"); byte[] authEncBytes = Base64.encodeBase64(credentials.getBytes()); String authStringEnc = new String(authEncBytes); System.out.println(authStringEnc); } }