I am trying to implement spring boot security with mysql and JPA. Post implementing the security whenever i am trying to hit any api using swagger it is continuously asking to enter username and password, even after entering correct user name and password multiple time it's thowing same pop up.
Below are the java classes and error screen shot
'''
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeHttpRequests()
.antMatchers("/student/updateStudent").hasRole("USER")
.antMatchers("/swagger-ui").permitAll()
.and()
.httpBasic();
httpSecurity.csrf().disable();
}
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
#Service
public class CustomUserDetailService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
return new CustomUserDetails(username);
}
}
public class CustomUserDetails implements UserDetails {
private String userName;
public CustomUserDetails(String userName) {
super();
this.userName = userName;
}
public CustomUserDetails() {
super();
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
}
#Override
public String getPassword() {
// TODO Auto-generated method stub
return "password";
}
#Override
public String getUsername() {
// TODO Auto-generated method stub
return userName;
}
#Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
'''
Related
I am new to libgdx and I wonder if you should use the render() method to get user input or if you should use the InputProcessor.
That depends on the use-case. Why do you need it and does that need to be done event driven or continuous?
For example, if you want to move a sprite on the screen while a certain key is pressed, then that's a continuous action:
#Override public void render() {
if (Gdx.input.isKeyPressed(Input.Keys.SPACE))
sprite.translateX(speed * Gdx.graphics.getDeltaTime());
...
}
However, if you for example want to change the color when the user presses a certain key, then that's an event:
#Override public void create() {
Gdx.input.setInputProcessor(new InputAdapter() {
#Override public boolean keyUp (int keycode) {
if (keycode == Input.Keys.SPACE)
sprite.setColor(Color.RED);
}
});
...
}
Note that polling is a convenience method built on top of events, it is very easy to that yourself. Like so:
private boolean moving;
#Override public void create() {
Gdx.input.setInputProcessor(new InputAdapter() {
#Override public boolean keyDown (int keycode) {
if (keycode == Input.Keys.SPACE)
moving = true;
}
#Override public boolean keyUp (int keycode) {
if (keycode == Input.Keys.SPACE)
moving = false;
}
});
...
}
#Override public void render() {
if (moving)
sprite.translateX(speed * Gdx.graphics.getDeltaTime());
...
}
This often allows you to write more clean and use-case specific code, like so:
private float speed;
#Override public void create() {
Gdx.input.setInputProcessor(new InputAdapter() {
#Override public boolean keyDown (int keycode) {
switch (keycode) {
case Input.Keys.LEFT: speed -= 10f; break;
case Input.Keys.RIGHT: speed += 10f; break;
}
}
#Override public boolean keyUp (int keycode) {
switch (keycode) {
case Input.Keys.LEFT: speed += 10f; break;
case Input.Keys.RIGHT: speed -= 10f; break;
}
}
});
...
}
#Override public void render() {
sprite.translateX(speed * Gdx.graphics.getDeltaTime());
...
}
With this in mind, it can in many cases be better to use event driven input handling. However, if you find yourself using a lot of boolean flags, then you might as well use the builtin input polling.
You should use InputProcessor for user input.
if you want to write anonymously then in show method you should write:-
Gdx.input.setInputProcessor(new InputProcessor() {
#Override
public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDragged(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyUp(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyDown(int arg0) {
// TODO Auto-generated method stub
return false;
}
});
or you can implement input processor and register instance in setInputProcessor.
Example:-
public class InputTest implements InputProcessor {
#Override
public boolean keyDown(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyUp(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDragged(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
}
in show method of your screen class you should write:-
public void show() {
Gdx.input.setInputProcessor(new InputTest());
}
in my suggestion these two are the best way to take user input if you are not using stage.
Hope this will work for you.
My hibernate configuration class include following code
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
My package structures like this enter code here
My daoImpl class like this.
#Repository("passArrayDao")
public class PassArrayDaoImpl extends AbstractDao<Integer, Arr> implements PassArrayDao {
#Override
public void passarray(Arr arr) {
}
}
normally we user hibernate for insert update delete data no.
#Override
public Book findBookById(int id) {
return bookDao.findBookById(id);
}
#Override
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
#Override
public List<Book> findBooksByTitle(String title) {
return bookDao.findBooksByTitle(title);
}
#Override
public void deleteBookById(int id) {
bookDao.deleteBookById(id);
}
#Override
public void updateBook(Book book) {
bookDao.updateBook(book);
}
bus now i want write insert query into daoImpl class. How I create it.
Hi everybody!!
I have two fragments:Fragment1 and Fragment2; Fragment1 contains Json,and after getting Json, I replace Fragment1 to Fragment2 via .replace(..) and transfer the Json via Bundle.
My Goal is: Refresh Json in Fragment1 each 60s for example and update automatically Fragment2 but i don't know how to do that!! i need your help!!
this is my code:
Class Fragment1
public class Fragment1 extends Fragment implements OnClickListener{
public static final String IMAGE_RESOURCE_ID="iconResourceID";
public static final String ITEM_NAME="itemName";
Button btnvalider;
//test transfer variable entre fragment
public Communicator com;
public void setCom(Communicator com) {
this.com = com;
}
/*
* Test Jsonparser
*
*/
Context c;
private ProgressDialog pDialog;
public String testfinalewa="";
JSonParser jsonParser = new JSonParser();
// url to create new product
private static String url_create_product = "http://10.0.2.2/webservice/create_personne.php";
public String getTestfinalewa() {
return testfinalewa;
}
public void setTestfinalewa(String testfinalewa) {
this.testfinalewa = testfinalewa;
}
// JSON Node names
private static final String TAG_SUCCESS = "success";
//fin test json
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
c=getActivity();
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnvalider=(Button)getActivity().findViewById(R.id.button1);
btnvalider.setOnClickListener(this);
this.com=(Communicator) getActivity();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
public void run() {
// call JSON methods here
new AttemptLogin().execute();
}
}, 1 );
}
//interface pour transferer variable entre fragment
public interface Communicator{
public void respond(String data);
}
class AttemptLogin extends AsyncTask<String, String, String>{//<params,progress,result>
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(c);
pDialog.setMessage("Chargement...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String name ="test";// pseudo.getText().toString();
String moddepasse = "test";//mdp.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
Log.i("misy ve", "ok="+moddepasse);
Log.i("misy ve", "ok="+name);
params.add(new BasicNameValuePair("moddepasse", moddepasse));
Log.i("test", "mbola tena mety eto 1");
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Create Response", json.toString());
Log.i("test", "mbola tena mety eto");
try {
int success = json.getInt(TAG_SUCCESS);
String succ=json.getString("ok");
Log.i("milay", succ);
if ((success == 1)) {
Log.i("accepter", "mdp correct");
} else {
Log.i("pas accepter", "non correct");
}
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
protected void onPostExecute(String result) {
pDialog.dismiss();
com.respond(result);
Fragment2 fb=new Fragment2();
FragmentTransaction t=getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("mondata", result);
fb.setArguments(args);
t.replace(R.id.myFramePrincipal, fb).commit();
}
}
}
class Fragment2
public class Fragment2 extends Fragment{
TextView text;
String aa;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView1);
text.setText(getArguments().getString("mondata"));
}
public void refreshData(String data) {
aa= new String(data);
//aa.notifyDataSetChanged();
text.setText(aa);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_3, container, false);
}
public void ChangerText(String data) {
text.setText(data);
}
}
Thanks for your help!!
I'm coding an integration Test for my Rest Application. I wrote a test to check accesDenied and it raises an UsernameNotFoundException, which it should, yet it does not follow the exception to the #ControllerAdvice class which returns a JSON.
The code works correctly in execution, returning the Json, and in other test cases like AuthenticationFailed - whcih is also handled by an exception -, the Json is return on running the test. The json is not return in this case, maybe because I have a custom UserDetailsService?
I've seen on the internet, others just test if exception was raised, and call the day. Yet I'd like the test to return same behaviour as execution - the Json. Is it possible? What am I missing?
I tried similar questions' answers but they didn't work, same behaviour was returned.
Any help would be much appreciated. Thx in advance,
Alfonso
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestConfig.class })
#WebAppConfiguration
public class SecurityIntegrationTest {
private final String SECURED_URI = "/users/1";
private final String LOGIN_URI = "/login";
#Autowired
private WebApplicationContext wac;
#Autowired
private FilterChainProxy springSecurityFilter;
#Autowired
CustomUserDetailsService customUserDetailsService;
#Autowired
UserController userController;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.addFilters(springSecurityFilter).alwaysDo(print()).build();
}
#Test
public void requiresAuthentication() throws Exception {
mockMvc.perform(
get(SECURED_URI).contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(status().isUnauthorized())
.andExpect(
content().contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(content().string(Jsons.AUTHENTICATION_REQUIRED));
}
#Test
public void authenticationFailed() throws Exception {
mockMvc.perform(formLogin())
.andExpect(status().isUnauthorized())
.andExpect(
content().contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(content().string(Jsons.AUTHENTICATION_FAILED));
}
#Test
public void authenticationSuccess() throws Exception {
mockMvc.perform(formLogin().user("Ikos").password("Ikos"))
.andExpect(status().isOk())
.andExpect(
content().contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(
content().string(
String.format(Jsons.LOGIN, "Ikos", "Ikos")));
}
#Test
public void accessGranted() throws Exception {
UserDetails user = customUserDetailsService.loadUserByUsername("Ikos");
mockMvc.perform(
get(SECURED_URI).with(user(user)).contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(status().isOk())
.andExpect(
content().contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(content().string(RestDataFixture.defaultUserJSON()));
}
#Test
public void accessDenied() throws Exception {
UserDetails user = customUserDetailsService.loadUserByUsername("Pedro");
mockMvc.perform(
get(SECURED_URI).with(user(user)).contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(status().isUnauthorized())
.andExpect(
content().contentType(
MediaType.valueOf(Constants.REST_TYPE)))
.andExpect(content().string(Jsons.AUTHENTICATION_REQUIRED));
}
}
#Configuration
#ComponentScan(basePackages = { "es.aekia.rest" })
#EnableWebMvc
public class TestConfig {
}
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDao;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user;
try {
user = userDao.findByAlias(username);
if (user == null)
throw new UsernameNotFoundException("user name not found");
} catch (DataAccessException e) {
throw new UsernameNotFoundException("database error");
}
return buildUserFromUserEntity(user);
}
private UserDetails buildUserFromUserEntity(User userEntity) {
// convert model user to spring security user
String username = userEntity.getAlias();
String password = userEntity.getPassword();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"
+ userEntity.getRole());
authorities.add(authority);
UserDetails springUser = new org.springframework.security.core.userdetails.User(
username, password, authorities);
return springUser;
}
}
#ControllerAdvice
public class ExceptionController {
#RequestMapping(produces = { Constants.REST_TYPE })
#ExceptionHandler({ MissingServletRequestParameterException.class,
UnsatisfiedServletRequestParameterException.class,
HttpRequestMethodNotSupportedException.class,
ServletRequestBindingException.class,
MethodArgumentNotValidException.class })
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public #ResponseBody Map<String, Object> handleRequestException(Exception ex) {
Map<String, Object> map = Maps.newHashMap();
map.put(Constants.ERROR, Constants.REQUEST_ERROR);
map.put(Constants.CAUSE, ex.getMessage());
return map;
}
#RequestMapping(produces = { Constants.REST_TYPE })
#ExceptionHandler(HttpMediaTypeNotSupportedException.class)
#ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public #ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(
HttpMediaTypeNotSupportedException ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put(Constants.ERROR, Constants.UNSUPPORTED_MEDIA_TYPE);
map.put(Constants.CAUSE, ex.getLocalizedMessage());
map.put(Constants.SUPPORTED, ex.getSupportedMediaTypes());
return map;
}
#RequestMapping(produces = { Constants.REST_TYPE })
#ExceptionHandler({ AccessDeniedException.class,
UsernameNotFoundException.class })
#ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public #ResponseBody Map<String, Object> handleAccesDeniedException(
Exception ex) {
Map<String, Object> map = Maps.newHashMap();
map.put(Constants.ERROR, Constants.ACCESS_DENIED);
map.put(Constants.CAUSE, ex.getMessage());
return map;
}
#RequestMapping(produces = { Constants.REST_TYPE })
#ExceptionHandler(Exception.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public #ResponseBody Map<String, Object> handleUncaughtException(
Exception ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put(Constants.ERROR, Constants.UNKNOWN_ERROR);
if (ex.getCause() != null) {
map.put(Constants.CAUSE, ex.getCause().getMessage());
} else {
map.put(Constants.CAUSE, ex.getMessage());
}
return map;
}
}
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
private RestAccessDeniedHandler restAccessDeniedHandler;
#Autowired
private RestAuthSuccessHandler restAuthSuccessHandler;
#Autowired
private RestAuthFailureHandler restAuthFailureHandler;
#Autowired
private RestLogoutSuccessHandler restLogoutSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
/*
* .authenticationProvider(authenticationProvider())
*/
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.accessDeniedHandler(restAccessDeniedHandler)
.and()
.formLogin()
.permitAll()
.loginProcessingUrl("/login")
// .usernameParameter(USERNAME)
// .passwordParameter(PASSWORD)
.successHandler(restAuthSuccessHandler)
.failureHandler(restAuthFailureHandler).and()
.logout()
.permitAll()
// .logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_PATH,
// "DELETE"))
.logoutSuccessHandler(restLogoutSuccessHandler).and()
.sessionManagement().maximumSessions(1);
// .logoutSuccessUrl("/logout").and()
/*
* .sessionManagement() .sessionCreationPolicy (SessionCreationPolicy
* .STATELESS).and()
*/
//
http.authorizeRequests().antMatchers(HttpMethod.POST, "/login")
.permitAll().antMatchers(HttpMethod.POST, "/logout")
.authenticated().antMatchers(HttpMethod.GET, "/users")
.permitAll().antMatchers(HttpMethod.GET, "/users/**")
.hasAnyRole("USER", "ADMIN")
.antMatchers(HttpMethod.POST, "/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/**").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/**").hasRole("ADMIN");
// .anyRequest().anonymous();
}
}
I can't seem to catch exceptions such as NoResultException or EJBException in my java ee 6 project. Is there something I am doing wrong? I have caught exceptions outside the EJB container but this is my first time using EJB. Thanks.
#Stateless
public class UserEJB {
#PersistenceContext
EntityManager em;
public String getUserName(User user) {
return user.getName();
}
public User fetchUserByEmail(String email) {
User user = em.createNamedQuery("User.findByEmail", User.class).setParameter("email", email).getSingleResult();
return user;
}
public User fetchUserById(int id) {
return em.createNamedQuery("User.findByUserId", User.class).setParameter("userId", id).getSingleResult();
}
public List<User> fetchAllUsers() {
return em.createNamedQuery("User.findAll", User.class).getResultList();
}
}
#Named(value = "userController")
#RequestScoped
public class UserController {
private User user = new User();
#EJB
UserEJB userEJB;
#Inject
SecurityController securityController;
public UserController() {
}
public void login(ActionEvent event) {
try {
User userLogin = userEJB.fetchUserByEmail(user.getEmail());
} catch (Exception e) {
}
if (userLogin.getPassword().equals(user.getPassword())) {
securityController.setIsLoggedIn(true);
securityController.setIsAdmin(true);
securityController.setUser(user);
}
}
/**
* #return the user
*/
public User getUser() {
return user;
}
/**
* #param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
What if you put two System.out.printlns in the code? One in the exception handler and one right before the if statement. What do you get?
Looking at the code I would say you would be able to catch the exception, which should be a JPA exception wrapped in an EJB one.